Skip to content

Instantly share code, notes, and snippets.

@jongan69
Last active January 30, 2023 05:01
Show Gist options
  • Save jongan69/e117f1e59060eecb26f45746487e6e62 to your computer and use it in GitHub Desktop.
Save jongan69/e117f1e59060eecb26f45746487e6e62 to your computer and use it in GitHub Desktop.
A Custom React Hook using Ref Pattern

useTimeout

A custom React Hook that allows you to call a callback after a specified delay.

Usage

import { useTimeout } from './useTimeout';

const callback = () => {
  // Do something
};

const delay = 1000;

useTimeout(callback, delay);

Parameters

  • callback: A callback function that will be called after the specified delay.
  • delay: The delay in milliseconds after which the callback will be called.
const useTimeout = (callback, delay) => {
const callbackRef = useRef(callback);
useLayoutEffect(() => {
callbackRef.current = callback;
});
useEffect(() => {
const id = setTimeout(() => callbackRef.current(), delay);
return () => clearTimeout(id);
}, [delay]);
};
@jongan69
Copy link
Author

This documentation was generated by AI Readme Generator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment