0
votes

I am migrating a react app from component to functional with hooks. The problem I'm facing is that we have a nested setState using callbacks. useState doesn't have this feature. I know I could use useEffect but there are functions that fire different functions depending on who triggered the change of a single state like the ones below. These can be isolated using the callback of setState but I'm wondering how to convert such using hooks. The only thing I have in mind is nesting a useEffect which is a bad idea based on the docs, you shouldn't loop/nest hooks.

setState({
   state1: "",
   state2: "",
}, () => {
    setState({
       state3: ""
    }, () => {
       function 1
    })
})

setState({
   state1: "",
   state2: "",
}, () => {
    setState({
       state3: ""
    }, () => {
       function 2
    })
})
1
Why do you have a nested setState? Why not just do both state changes in the same call? That way you only need the one useEffect, the final done after the state changes.Jayce444

1 Answers

0
votes

You probably can do something like this, I'm not sure if that's the best way to do

useEffect(() => {
  setState1;
  setState2
}, [])

useEffect(() => {
// you will need some logic here to prevent inital run
// like say if state1 and state2 is at inital state, don't set state3
  setState3;
}, [state1, state2])

useEffect(() => {
// same idea, you will need logic from state3 to prevent inital run
  func1
}, [state3])