useTimeout hook

Executes function after given ms interval

useTimeout hook
import { useEffect, useLayoutEffect, useRef } from 'react';

export function useTimeout(callback: () => void, delay?: number) {
  const callbackRef = useRef(callback);

  useLayoutEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  useEffect(() => {
    if (!delay && delay !== 0) {
      return;
    }

    const id = setTimeout(() => callbackRef.current(), delay);

    return () => clearTimeout(id);
  }, [delay]);
}

Usage

import React, { useState } from 'react';
import { useTimeout } from './use-timeout';

export default function App() {
  const [visible, setVisible] = useState(true);

  const hide = () => setVisible(false);

  useTimeout(hide, 5000);

  return (
    <div>
      <p>{visible ? 'Hi' : null}</p>
    </div>
  );
}