Here's how to use setInterval inside a React functional component safely with TypeScript. It's important to cleanup the call after the component is unmounted so that the recurring function call does not keep runnning in the background.
This code allows your React Component to repeatedly call a function every X seconds. The code is in TypeScript, but you can easily remove the typing if you're using plain JavaScript.
Contents
The Code
MyComponent.tsx
import React, { useRef, useEffect } from 'react';
const MyComponent = () => {
const interval = useRef<NodeJS.Timeout>();
useEffect(() => {
if (interval.current === undefined) {
interval.current = setInterval(() => {
// do something every 1000 milliseconds
}, 1000)
}
return () => {
if (interval.current !== undefined) {
clearInterval(interval.current);
interval.current = undefined;
}
}
}, [])
return <div>My Component Message</div>;
}
useEffect for mounting and unmounting
The empty dependencies []
denotes that this useEffect will run when our component mounts, starting the recurring functional call set by setInterval
.
The return () => { ...
function here runs when the component unmounts. It's critical we call clearInterval
here to remove the interval that we create when mounting so that it does not continue to run when the component is no longer required.
setInterval's return value
interval.current = setInterval(() => {}, 1000)
setInterval
will re-run a function every X
milliseconds, in this case 1000
milliseconds (1 second). Note that it will run the very first function call after the set 1 second, and not immediately at the time the setInterval is initially called.
setInterval
(similar to setTimeout
) returns an ID number that represents the interval that is set. Calling clearInterval
on this number will remove the interval loop, preventing it from being called again.
useRef for storing interval ID
const interval = useRef<NodeJS.Timeout>();
useRef
is used here to store the interval ID reference. useRef
is ideal because the interval ID number shouldn't trigger re-renders, and its value should be consistent between renders.
Alternatives
There shouldn't be many scenarios where this functionality is used too frequently, as there may be better ways to implement your recurring function call design properly, instead. Also, you could implement this functionality as a hook for re-use if required.
No comments:
Post a Comment