Implement a useTimeout hook that invokes a callback function after a specified delay.

Note that the hooks can be called again with different values since the initial call:

The primary benefit of useTimeout is so that you don't have to manually clear call clearTimeout() if the component unmounts before the timer expires.

export default function Component() {
  const [loading, setLoading] = useState(true);

  useTimeout(() => setLoading(false), 1000);

  return (
    <div>
      <p>{loading ? 'Loading' : 'Ready'}</p>
    </div>
  );
}

Arguments

  1. callback: () => void: A function to be called after the specified delay
  2. delay: number | null: The delay in milliseconds before the invocation of the callback function. If null, the timeout is cleared

Returns

Nothing.

Editorial