skip to Main Content

I have an issue with the states not updating properly (stale closure). I am first setting index 0 of activeCards and console logging it (the first entry in the log provided). This log returns the result of the state as it was prior to it being updated. Then I am setting index 1 of the same and console logging it (second entry in the log provided). The second log returns the result as it was prior to the second update (ie as it should’ve been logged after the previous update). How can I update a state immediately or else wait for it to be updated before I proceed?

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

if(condition){
        temp = [...activeCards];
        temp[0] = {index: index, url: cards[index]};
        setActiveCards([...temp])
        console.log(activeCards)
}
else{

        temp = [...activeCards];
        temp[1] = {index: index, url: cards[index]};
        setActiveCards([...temp])
        console.log(activeCards)
}

enter image description here

4

Answers


  1. Chosen as BEST ANSWER

    The best way to solve stale closures is to use useRef() instead of useState() for values which one requires to be updated frequently. Hence one will avoid having a large number of states being updated sequentially causing a stale closure.


  2. let temp = [activeCards];
    

    This makes temp a 2d array since activeCards itself is an array. Maybe what youre intending to do is,

    let temp = [...activeCards];
    
    Login or Signup to reply.
  3. state not update immediately for performance. if you use functional component you can use the useEffect(()=>{//code run after state updated},[your state]) and it call every time your state update to new value. and if you are using class component you can use this.setState({someState:”}, () => {
    //code run after state updated
    });

    Login or Signup to reply.
  4. You can do like this.

        useEffect(() => {
        console.log(activeCards);
    }, [activeCards]);
    
    let temp = [...activeCards];
    temp[0] = { index: index, url: cards[index] };
    if (!condition) {
        temp[1] = { index: index, url: cards[index] };
    }
    setActiveCards([...temp]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search