Languages
[Edit]
EN

React - setInterval example

0 points
Created by:
JoanneSenior
1070

In this article, we would like to show you setInterval method example in React

Quick solution:

React.useEffect(() => {
    const callback = () => {
        console.log('interval...');
    };
    const handle = setInterval(callback, 1000); // called once per 1 second
    return () => clearInterval(handle);
}, []);

setInterval is a method that takes in two arguments:

  • a function which is being called every specific amount of time (interval),
  • the interval time (in milliseconds).

setInterval is executed until it's stopped by clearInterval method which takes the interval as an argument.

Below we present some practical examples for better understanding.

 

Simple setInterval example

In this example we use useEffect() hook to run the callback() function inside it when the App component is first rendered. The useEffect() returns a clearInterval() function, which means it will be executed when it is time to clean up (on App component unmount).

// ONLINE-RUNNER:browser;

//import React from 'react';
//import ReactDOM from 'react-dom';

const App = () => {
    React.useEffect(() => {
        const callback = () => {
            console.log('interval...');
        };
        const handle = setInterval(callback, 1000); // called once per 1 second
        return () => clearInterval(handle);
    }, []);
    return (
        <div>Component body here...</div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

 

Reusable hook example

In this example, we create a reusable useInterval component that takes two arguments:

  1. callback - a function to be executed repeatedly with a fixed time delay between each call,
  2. interval - the time delay between each call.

We use the custom setInterval in MyComponent to display some text in the console every 1000 milliseconds (1 second) on the component mount.

// ONLINE-RUNNER:browser;

// import React from 'react';
// import ReactDOM from 'react-dom';

const useInterval = (callback, interval) => {
    const ref = React.useRef();
    ref.current = callback;
    React.useEffect(() => {
        const handle = setInterval(() => ref.current?.(), interval);
        return () => clearInterval(handle);
    }, [interval]);
};


// Usage example:

const MyComponent = () => {
	useInterval(() => console.log('interval...'), 1000);
    return (
      <div>Component body here...</div>
    );
};

const App = () => {
    const [visible, setVisible] = React.useState(false);
    return (
      <div>
        <button onClick={() => setVisible(true)}>Mount MyComponent</button>
        <button onClick={() => setVisible(false)}>Unmount MyComponent</button>
        {visible && <MyComponent />}
      </div>
    );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

 

See also

  1. React - useEffect hook

Related posts

Alternative titles

  1. React - setInterval & clearInterval
  2. React - setInterval with useEffect hook
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join