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)
}
4
Answers
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.
This makes temp a 2d array since activeCards itself is an array. Maybe what youre intending to do is,
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
});
You can do like this.