-
Notifications
You must be signed in to change notification settings - Fork 0
useTimeout
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
A declarative setTimeout hook that safely handles cleanup. It automatically clears the timeout when the component unmounts and guarantees that you always have access to the latest state inside your callback.
The simplest possible implementation, which starts the timeout immediately on mount.
import { useState } from 'react';
import { useTimeout } from 'react-hook-lab';
function BasicTimeout() {
const [show, setShow] = useState(true);
useTimeout(() => {
setShow(false);
}, 5000);
if (!show) return null;
return <div>This will disappear in 5 seconds!</div>;
}Manually stopping or restarting the timeout based on user interaction.
import { useState } from 'react';
import { useTimeout } from 'react-hook-lab';
function AutoLogout() {
const [loggedOut, setLoggedOut] = useState(false);
const { restart, clear } = useTimeout(() => {
setLoggedOut(true);
}, 60000); // 1 minute of inactivity
if (loggedOut) return <div>You have been logged out due to inactivity.</div>;
return (
<div onMouseMove={restart} onKeyDown={restart}>
<p>Move your mouse or press a key to reset the inactivity timer.</p>
<button onClick={clear}>Disable Auto-Logout</button>
</div>
);
}An exhaustive example checking the active status and dynamically controlling the execution flow.
import { useState } from 'react';
import { useTimeout } from 'react-hook-lab';
function AdvancedTimeout() {
const [logs, setLogs] = useState<string[]>([]);
const { start, clear, isActive } = useTimeout(() => {
setLogs(prev => [...prev, `Timeout triggered at ${new Date().toLocaleTimeString()}`]);
}, 3000);
return (
<div>
<p>Status: {isActive() ? 'Running' : 'Stopped'}</p>
<button onClick={start} disabled={isActive()}>Start Timer</button>
<button onClick={clear} disabled={!isActive()}>Stop Timer</button>
<ul>
{logs.map((log, i) => <li key={i}>{log}</li>)}
</ul>
</div>
);
}-
callback(Required)- Type:
() => void - Description: The function to execute after the delay. This callback is internally wrapped in a ref, so you do not need to wrap it in
useCallbackto prevent infinite loops. It always has access to the latest state.
- Type:
-
delay(Required)- Type:
number - Description: The delay in milliseconds before executing the callback.
- Type:
Returns UseTimeoutReturn:
-
start(() => void): Function to manually start or restart the timeout from 0. -
clear(() => void): Function to manually cancel the running timeout. -
restart(() => void): Alias forstart(). Clears and starts the timeout. -
isActive(() => boolean): Returnstrueif the timeout is currently counting down, orfalseif it has fired or been cleared.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM