Home > Mobile >  React state change is one step behind
React state change is one step behind

Time:11-27

A common problem in React, especially among beginners (like me). This is due to the fact that setState is an asynchronous function and React does not change values one by one, but accumulates some pool if it is not otherwise instructed. (please correct me if the wording is wrong)

So here's the question. One simple solution is to put the desired state into the useEffect dependency array. For example, I have such a component:

const [first, setFirst] = useState()
const [second, setSecond] = useState()

useEffect(() => {
    Something logic by first and second...
}, [first])

Here, the useEffect is executed every time the first state changes. At the same time, at the moment of its operation, the second state is not relevant, next time it will become as it should be now, and so on. Always one step behind.

But if I add a second state to the useEffect dependency array, then everything works as it should.

useEffect(() => {
    Something logic by first and second...
}, [first, second])

At the same time, it is not necessary that the useEffect work on changing the second state, I added it only in order to have an up-to-date version inside the useEffect. Can I use the useEffect dependency array this way?

CodePudding user response:

if you use useEffect with an empty array it will act as componentDidMount and componentWillUnmount so it will only invoke itself on first component creation and when it is about to unmount.

https://reactjs.org/docs/react-component.html#componentdidmount

CodePudding user response:

Here I got the problem You are facing, I am not fully sure, but In my case I was console.log(result) withing the fucntion that was changing state, but it was always one step behind. why was that? because in React it is considered as side effect. So If you console.log(result) in useEffect passing the value in dependency array then, it will console log the same value that instantly changed. In backgorund the state is updating exactly the same time but useEffect detects it as exactly as it is changed. You can write any logic in useEffect as well or in the function which you are updating. So there should not be any problem writing logic in the function which you are callilng on click.

  • Related