0

Here is my app code:

const [myState, setMyState] = useState(() => {
    return {
        flag1: false,
        flag2: false
    }
})

useEffect(() => {
    console.log(myState)
}, [myState])

setMyState({ ...myState, flag1: true })

Last row triggers useEffect() but console output shows old state:

{flag1: false, flag2: false}

What am I doing wrong? I want to watch when all flag fields and once these are true - then I'll execute some code in useEffect. What would be best approach to do it?

John Glabb
  • 1,336
  • 5
  • 22
  • 52
  • on which method did you call `setMyState`? – wangdev87 Feb 03 '21 at 04:17
  • The effect callback runs *after* a render, and a state update triggers a rerender, the console log in the effect will be the current state. Is this your actual code? – Drew Reese Feb 03 '21 at 04:18
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – nsrCodes Feb 03 '21 at 04:18

1 Answers1

0

You dont need a function in useState.

Use prevState in setMyState, this way you will get the current state values

const [myState, setMyState] = useState( {
        flag1: false,
        flag2: false
    });

useEffect(() => {
    console.log(myState)
}, [myState])

setMyState(prevState=>({ ...prevState, flag1: true }));
kiranvj
  • 32,342
  • 7
  • 71
  • 76
  • 1
    Lazy state initialization is still ok though, albeit probably unnecessary in this simplified example, and IMO not an issue here. https://reactjs.org/docs/hooks-reference.html#lazy-initial-state – Drew Reese Feb 03 '21 at 04:26
  • @DrewReese Yes, I totally agree. – kiranvj Feb 03 '21 at 06:23