setInterval In React (StrictMode)

steveleung9527
May 16, 2022

--

This tutorial teach you how to use setInterval in useEffect, and prevent unexpected multiple setInterval run in useEffect when state is updated.

Problem

In this code, we set our interval 1s to update “count”, but in fact, the count is updated twice in a second. Why??? It is because of the React.StrictMode.

React.StrictMode only works on development environment, and will at least render twice the <App /> component to help you find out

  • unstable lifecycles
  • deprecated findDomNode usage
  • unexpected side effects
  • and detecting legacy context API

In this case, it helps us find out that we didn’t add the clean up effect in our useEffect hooks. Here is how we can fix it.

useEffect cleanup function

Addition

you can use useRef to store the setInterval

Please follow me if you find information is useful~

--

--