0

I am having one component where I need to handle multiple states that's why i have declared multiple states. is there way to optimise states in hooks component.

const [showPopup, setShowPopup] = useState(false);
  const [camPopup, setCamPopup] = useState(false);
  const [color, setColor] = useState("red");
 const [userdata, setUserdata] = useState(null);

and few more states are there how to optimise/ reduce them.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
jeevan
  • 67
  • 1
  • 13
  • What you've written looks perfectly fine to me, what is your motivation behind trying to optimise it? As long as the states are not interdependant, your current approach is the correct one. What you can do to improve readability is to group similar states into custom hooks, but I wouldn't go much further than that. – Filip Kaštovský Apr 06 '22 at 07:15
  • @FilipKaštovský it's working as expected but the problem is it's looking weird when i need to add more states in the component. – jeevan Apr 06 '22 at 10:11

1 Answers1

1

You can put them in an object with useState:

const [state, setState] = useState({
    showPopup: false,
    camPopup: false,
    color: "red",
    userdata: null,
});

// Destructure state, so we don't have to write state.something everytime
const {showPopup, camPopup, color, userdata} = state; 

But note that, in a complex state, we can also use useReducer:

const initialState = {
    showPopup: false,
    camPopup: false,
    color: "red",
    userdata: null,
}

const [state, dispatch] = useReducer(reducer, initialState);

const {showPopup, camPopup, color, userdata} = state; // Destructure

function reducer(state, action) {
  switch (action.type) {
    case 'login':
      // we can't mutate state directly, but will have to return a new state object
      return {...state, userData: action.payload}; 
    default:
      throw new Error();
  }
}
Enfield Li
  • 1,952
  • 1
  • 8
  • 23
  • in your first option object with useState:.. what if I want update a single state in that object . how can i do that. – jeevan Apr 06 '22 at 10:13
  • The logic is the same, you can't mutate state directly, but will have to return a new state object: setState({...state, userData: yourData}), also check out this question: https://stackoverflow.com/questions/54150783/react-hooks-usestate-with-object – Enfield Li Apr 06 '22 at 10:17
  • Yep, happy to help – Enfield Li Apr 06 '22 at 10:20