Home > @cascadiacollections/fluentui-compat > useSetTimeout
useSetTimeout() function
Hook to provide performance optimized timeout management with automatic cleanup.
This hook provides a wrapper around setTimeout
and clearTimeout
that: - Automatically cleans up all active timeouts when the component unmounts - Uses Set for O(1) add/remove operations instead of Record for better performance - Auto-removes timeouts from tracking when they execute naturally - Returns a memoized object to prevent unnecessary re-renders
Signature:
useSetTimeout: () => UseSetTimeoutReturnType
Returns:
An object containing setTimeout and clearTimeout functions with automatic cleanup
Example 1
import { useSetTimeout } from '@cascadiacollections/fluentui-compat';
import { useCallback } from 'react';
function MyComponent() {
const { setTimeout, clearTimeout } = useSetTimeout();
const handleClick = useCallback(() => {
const timeoutId = setTimeout(() => {
console.log('Delayed action executed');
}, 1000);
// Optionally clear the timeout early
// clearTimeout(timeoutId);
}, [setTimeout, clearTimeout]);
return <button onClick={handleClick}>Start Timer</button>;
}
Example 2
// Multiple timeouts with cleanup
function TimerComponent() {
const { setTimeout } = useSetTimeout();
React.useEffect(() => {
// Set multiple timeouts
setTimeout(() => console.log('First'), 1000);
setTimeout(() => console.log('Second'), 2000);
setTimeout(() => console.log('Third'), 3000);
// All timeouts will be automatically cleaned up on unmount
}, [setTimeout]);
return <div>Timer Component</div>;
}