Categories
React Answers

How to fix setTimeout() not working with React?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *