Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks, one hook for each state value?

I am fairly new to Hooks and am very interested in using it for future projects/work. I am curious to learn more about what are the best practices in terms of using hooks for a component with many different states. As far as I know, for each state value, you would you use the useState hook.

Let's say for example we have a class based component with this state:

this.state = {
   state1: 0,
   state2: '',
   state3: false,
   state4: [],
   state5: {},
   state6: null
}

If I were to convert this using hooks... would best practices be to use useState for each state (a total of 6 useState) or is there a better way?

Thank you all!

like image 580
kennycodes Avatar asked Apr 12 '26 06:04

kennycodes


1 Answers

With my option, I think the best practice is:

   const [state1, setState1] = useState(0)
   const [state2, setState2] = useState('')
   const [state3, setState3] = useState(false)
   const [state4, setState4] = useState([])
   const [state5, setState5] = useState({})

Because each state local that you want to control is difference type. And you could control each variable more flexible.

But if you want to do with your case, you can do like that:

   const [state, setState] = useState({
       state1: 0,
       state2: ''
       state3: false
   })

And when update state1 and state2:

   setState({
      ...state,
      state1: 1,
      state2: "yada"
   })
like image 149
aldenn Avatar answered Apr 14 '26 18:04

aldenn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!