Test cleanup in a custom hook
Encapsulate an external timer
A Hook can hide the mechanics of an external synchronization while exposing clear inputs. A debounced value waits until the source value has remained unchanged for a specified delay. This can reduce noisy updates to a preview. The example uses a browser timer, not a server request, and the initial displayed value is immediate.
import React, { useEffect, useState } from 'react';function scheduleValue(clock, value, delay, publish) { const id = clock.setTimeout(() => publish(value), delay); return () => clock.clearTimeout(id);}function useDebouncedValue(value, delay = 300) { const [settled, setSettled] = useState(value); useEffect(() => scheduleValue(window, value, delay, setSettled), [value, delay]); return settled;}export default function App() { const [query, setQuery] = useState(''); const settled = useDebouncedValue(query, 300); return <main><label>Trail search <input value={query} onChange={e => setQuery(e.target.value)} /></label> <p>Search preview: {settled || '(empty)'}</p></main>;}Typing updates the input immediately. After a quiet period the preview catches up. The delay is a nonnegative millisecond value, not an exact delivery deadline. Both value and delay are reactive dependencies; a change cancels the previous timer and schedules another. Removing the component also clears the outstanding timer. No request cancellation is implied: a real fetch needs its own cancellation or stale-result guard.
Expose an explicit subscription contract
import React, { useEffect, useState } from 'react';function createChannel() { const listeners = new Set(); return { subscribe(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, publish(message) { for (const listener of [...listeners]) listener(message); }, size() { return listeners.size; } };}const channel = createChannel();function useAnnouncement(source) { const [message, setMessage] = useState('No announcement yet'); useEffect(() => source.subscribe(setMessage), [source]); return message;}function Notice() { return <p role="status">{useAnnouncement(channel)}</p>; }export default function App() { const [shown, setShown] = useState(true); return <main><button onClick={() => channel.publish('Trail open')}>Announce opening</button> <button onClick={() => setShown(v => !v)}>Toggle notice</button>{shown && <Notice />}</main>;}The channel delivers future messages to subscribers; it does not store the latest message. The notice initially shows no announcement. Once subscribed, activating Announce opening changes the notice. Hiding it removes the listener; showing it creates a fresh notice. This event-only fixture is not a general external-store adapter: useSyncExternalStore is the later topic for reading consistent store snapshots. Source is a stable module-level object; the dependency ensures a different source would replace the subscription. The current notice is not automatically reset when source changes.
Test visible behavior and cleanup separately
import React, { useEffect, useState } from 'react';function useDebouncedValue(value, delay) { const [settled, setSettled] = useState(value); useEffect(() => { const id = window.setTimeout(() => setSettled(value), delay); return () => window.clearTimeout(id); }, [value, delay]); return settled;}function Preview({query, delay}) { return <p>Preview: {useDebouncedValue(query, delay) || '(empty)'}</p>; }export default function App() { const [query, setQuery] = useState(''); const [delay, setDelay] = useState(300); const [shown, setShown] = useState(true); return <main><label>Query <input value={query} onChange={e => setQuery(e.target.value)} /></label> <label>Delay <select value={delay} onChange={e => setDelay(Number(e.target.value))}><option value={300}>300 ms</option><option value={600}>600 ms</option></select></label> <button onClick={() => setShown(v => !v)}>Toggle preview</button>{shown && <Preview query={query} delay={delay} />}</main>;}Use the harness to test fast typing, changing delay, unmounting before delivery and remounting. For automated UI tests in a reviewed React testing environment, use fake timers integrated with React updates and assert displayed text, rather than calling a Hook as an ordinary function. A renderHook harness is also useful for library contracts when supported. StrictMode may perform an extra development setup/cleanup cycle; verify no timer or listener leaks rather than assuming an exact number of renders. The pure timer scheduler and channel can be tested locally without React; that does not verify Hook lifecycle behavior. Practice: write a fake clock test for cancelling one pending delivery and a browser test for changing delay.