React - setInterval example
In this article, we would like to show you setInterval
method example in React.
Quick solution:
xxxxxxxxxx
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.
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).
xxxxxxxxxx
//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);
In this example, we create a reusable useInterval
component that takes two arguments:
callback
- a function to be executed repeatedly with a fixed time delay between each call,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.
xxxxxxxxxx
// 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);