JAVASCRIPT

React useTimeout Hook for Delayed Actions

Create a custom React hook to execute a callback function after a specified delay, useful for animations, notifications, or timed events.

import { useEffect, useRef } from 'react';

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

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    if (delay !== null) {
      const handler = setTimeout(() => savedCallback.current(), delay);
      return () => clearTimeout(handler);
    }
  }, [delay]);
}
How it works: The useTimeout hook provides a way to run a function after a specified delay, similar to `setTimeout`. It uses `useRef` to keep a stable reference to the `callback` function, ensuring it always calls the latest version without needing to re-create the timeout on every render. The `useEffect` cleanup function properly clears the timeout, preventing memory leaks and ensuring the callback only runs when intended.

Need help integrating this into your project?

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

Hire DigitalCodeLabs