JAVASCRIPT
Declarative Timers with useTimeout Hook in React
Create a custom React useTimeout hook to manage `setTimeout` calls declaratively, ensuring proper cleanup and preventing memory leaks in components.
import { useEffect, useRef } => 'react';
const useTimeout = (callback, delay) => {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
// Set up the timeout.
useEffect(() => {
if (delay !== null) {
const handler = () => savedCallback.current();
const id = setTimeout(handler, delay);
return () => clearTimeout(id);
}
}, [delay]);
};
// Example Usage:
// function Notification() {
// const [isVisible, setIsVisible] = useState(true);
//
// useTimeout(() => {
// setIsVisible(false);
// }, isVisible ? 3000 : null);
//
// return (
// <>
// {isVisible && (
// <div style={{ padding: '10px', background: 'lightgreen' }}>
// This notification will disappear in 3 seconds!
// </div>
// )}
// <button onClick={() => setIsVisible(true)}>Show Notification</button>
// </>
// );
// }
How it works: The `useTimeout` hook provides a declarative way to use `setTimeout` in React components. It takes a `callback` function and a `delay`. The `useRef` hook stores the latest `callback` to ensure the `setTimeout` always executes the most up-to-date function. The `useEffect` hook sets up the timer and automatically clears it when the component unmounts or when the `delay` changes, preventing common issues with `setTimeout` in React. Passing `null` as `delay` will prevent the timeout from running.