React Hooks With Javascript Intervals

Javascript intervals help us to manage actions that take time or perform behaviour that needs to be executed at a later point in time. Here’s a basic example of a javascript interval for a countdown clock.

let seconds = 0;
const intervalID = setInterval(() => {
 seconds++;
 console.log(‘seconds:’, seconds)
}, 1000);

In the above example we define “seconds” variable than we bump that variable every 1000ms (which is 1 second). Then we log it to the console to see if it works good. If we’d want to stop the interval we’ll use clearInterval with the intervalID variable.

Difference between Intervals and setTimeout

How To, With React and Hooks?

Since the nature of the interval code is async, we’d want to use react code that supports side effects. In this case we are going to use useEffect. useEffect is meant for any side effects in react, data fetching, dom manipulation or subscription.

const [seconds, setSeconds] = useState(60);

useEffect(() => {
 const interval = setInterval(() => {
 setSeconds(seconds => seconds — 1);
 }, 1000);

if(seconds <= 0) {
 clearInterval(interval);
 }

return () => clearInterval(interval);
 }, [seconds]);

In the above example we count from 60 to 0. And we use useEffect to manage the async nature of intervals. We also keep a const of the setInterval so we could use clearInterval later. Note that we also set seconds as a dependency for useEffect so whenever the number changes it will continue to run the useEffect and if the number is below 0, we’ll clear the interval.

Important

Remember to clean up any side effect that can be cleaned to prevent memory leaks and apps that will run indefinitely and crash. In the Interval case use clearInterval.

Leave a Reply

Your email address will not be published. Required fields are marked *

All rights reserved 2024 ©