React: How to use setInterval in useEffect to render the component each period of time?

Created on 10 Dec 2018  路  1Comment  路  Source: facebook/react

Do you want to request a feature or report a bug?
Do not know if it's a bug or miss of conception

What is the current behavior?

The component was displayed for a period of time then the app crashed due to this error:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    in Hello (created by App)
    in App

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

https://codesandbox.io/s/k5074zpkrv

What is the expected behavior?`
Display the interface and render the component.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

react: 16.7.0-alpha.2
react-version: 16.7.0-alpha.2
OS: windows 10

Most helpful comment

I think you're supposed to clear the interval or else it's going to keep making a new interval.

  useEffect(() => {
    const interval = setInterval(() => {
      setFirstOperand(Math.floor(Math.random() * 30));
      setSecondOperand(Math.floor(Math.random() * 30));
    }, 1000);

    return () => clearInterval(interval);
  });

>All comments

I think you're supposed to clear the interval or else it's going to keep making a new interval.

  useEffect(() => {
    const interval = setInterval(() => {
      setFirstOperand(Math.floor(Math.random() * 30));
      setSecondOperand(Math.floor(Math.random() * 30));
    }, 1000);

    return () => clearInterval(interval);
  });
Was this page helpful?
0 / 5 - 0 ratings