1

I'm tring to update a state and just after, to do other things with this state like this :

const [isStudent, setIsStudent] = useState<null | boolean>(null);

const onPressItem = (titre: string) => {
   [Do things...]
   setIsStudent(true);
   navigation.navigate('OtherScreen, {isStudent: isStudent});
}

The probleme is, in my OtherScreen, the variable isStudent egal null, like if setIsStudent(true) don't work right now.

Any solutions ?

samuel
  • 477
  • 7
  • 21
  • 1
    Setting the state has always been an async operation, but if you don't use hooks, you have a callback. If you use hooks, you don't have them. Check this: [How to use \`setState\` callback on react hooks](https://stackoverflow.com/questions/56247433/how-to-use-setstate-callback-on-react-hooks) – sjahan Sep 30 '20 at 07:01

1 Answers1

1

The hook is asynchronous and won't necessarily update immediately. If you need access to the updated value you can pass the current value as the first argument in the update function:

(currentState) => currentState + 1

You can also run a useEffect hook that will perform the update once the state has been updated. This is covered well by the chosen answer here: useState set method not reflecting change immediately

jacobedawson
  • 2,929
  • 25
  • 27