Sometimes, we want to fix setTimeout() not working with React.
In this article, we’ll look at how to fix setTimeout() not working with React.
How to fix setTimeout() not working with React?
To fix setTimeout() not working with React, we can use call setState in the setTimneout callback.
For instance, we write
setTimeout(() => this.setState({ position: 1 }), 3000);
to call setTimeout with a callback that calls this.setState.
We use an arrow function for the callback since it doesn’t bind to its own value of this.
This means this will still be the component instance.
Conclusion
To fix setTimeout() not working with React, we can use call setState in the setTimneout callback.