JAVASCRIPT

Implement Declarative Timed Actions with useInterval Hook

Create a custom React useInterval hook to run a function repeatedly at a specified delay, offering a clean and declarative way to manage animations or periodic tasks.

import { useEffect, useRef } from 'react';

function useInterval(callback, delay) {
  const savedCallback = useRef();

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  // Set up the interval.
  useEffect(() => {
    function tick() {
      savedCallback.current();
    }
    if (delay !== null) {
      let id = setInterval(tick, delay);
      return () => clearInterval(id);
    }
  }, [delay]); // Only re-run if delay changes
}
How it works: The `useInterval` hook provides a declarative way to execute a function repeatedly at a given `delay`. It's built using `useEffect` and `useRef` to ensure that the `callback` function always references its latest version without causing the interval to reset on every render. This is perfect for managing animations, simple counters, or any task requiring periodic execution in a React component.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs