Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Init UseState value from UseContext value

I have context and state variables. My state variable is initialized with my context variable. When I update my context in another component for exemple: changing the player’s action (attack to defend), state variable keep the previous value.

const [player,setPlayer] = useContext(PlayerContext);
const [action, setAction] = useState(player.action); 

useEffect(() => {
    console.log(action); // => attack
    console.log(player.action); // => defend
});

This must surely be a rendering problem.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want the action state variable to reflect updates to player.action, you need make sure your dependency array (the second parameter to useEffect) includes player.action (so that it only runs when the value changes), and then call setAction explicitly:

useEffect(() => {
   if (player.action !== action) {
      setAction(player.action);
   }
}, [player.action])

The React documentation has an extensive guide on Using the Effect Hook that might be helpful, along with the useEffect hook API reference.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading