Home > Back-end >  Init UseState value from UseContext value
Init UseState value from UseContext value

Time:11-14

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.

CodePudding user response:

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.

CodePudding user response:

Your context state is changed somewhere after your component is rendered. Therefore the component state is not in sync with the context state anymore. With your browsers debugger you can check this behaviour and find out where it is changed.

As a general rule you should avoid adding a component state, when it shall only mirror a context‘s state, consume the context directly inside your component.

  • Related