How it works
When and where @k8ordo/effects synchronizes with the browser, and what it does and does not guarantee.
On this page
Value hooks
online.tsconst subscribe = (onChange: () => void) => {
const controller = new AbortController();
const { signal } = controller;
window.addEventListener('online', onChange, { signal });
window.addEventListener('offline', onChange, { signal });
return () => {
controller.abort();
};
};
export const useOnline = (): boolean =>
useSyncExternalStore(
subscribe,
() => navigator.onLine,
Read in the browser
() => true,
Read on the server and while hydrating
);The three value hooks are built on React’s useSyncExternalStore. Its third argument is the value for the server render and the hydration render.
Once hydrated, React renders again straight away and reads the browser’s value from the second argument. A component mounted after hydration uses the second argument from its first render.
When subscriptions start and stop
events.tsexport const useWindowEvent = <K extends keyof WindowEventMap>(
type: K,
handler: (event: WindowEventMap[K]) => void,
): void => {
const onEvent = useEffectEvent(handler);
Always calls the latest handler
useEffect(() => {
const controller = new AbortController();
window.addEventListener(
type,
(event) => {
onEvent(event);
},
{ signal: controller.signal },
);
return () => {
controller.abort();
};
}, [type]);
Added again only when `type` changes
};Events, channels, timers and polls start in the component’s effect. Effects do not run on the server, so nothing subscribes there.
On unmount, the effect’s cleanup stops them. Listeners are removed together through an AbortController.
Handlers and callbacks are wrapped in useEffectEvent, and the effect depends only on type, name, ms, running or key. A new callback never restarts the subscription.
The scroll record
useScrollDirection keeps one record per threshold. The first component to subscribe adds the scroll listener, and the last one to unsubscribe removes it.
A record counts from window.scrollY when it is made, and is null until a direction is set.
A round of polling
A round calls poll, checks what it resolved to, and waits that long with setTimeout. A new key or an unmount aborts it through an AbortController and clears the pending timer.
A failure of poll is put in state, and the component fails with it in the next render. A failure after an abort is ignored.
The resource cache
A resource holds one promise per key, by the key’s JSON.stringify. The first read calls load and keeps the promise.
refresh(key) replaces the promise and re-renders the components reading that key. A refresh that lands between a render and its subscription re-renders too.
useResource calls use(browser()) first. On the server it stops there, so it never touches a cache.
Guarantees
- A value hook returns the server’s value on the server and in the hydration render, and the browser’s value right after. Hydration never mismatches.
- A
useResourcesubtree is never rendered on the server, andloadis called in the browser alone. - Handlers,
onMessage, timer callbacks andpollare the latest render’s when they run. Nothing restarts because a callback changed. - Listeners, channels, timers and polls start when the component mounts and stop when it unmounts. A poll in flight is aborted through its
signal. - A resource’s
loadis called once per key untilrefresh. useScrollDirectionwith the samethresholdreturns the same direction in every component.- A negative threshold, delay or poll interval throws an error that starts with the hook’s name. A key that would restart polling every render is a type error.
Not guaranteed
- What a value hook renders shows the server’s value until its boundary has hydrated.
useOnlinereadsnavigator.onLineand nothing else. It does not check that a server can be reached.setFullscreendoes not handle the rejection when the browser refuses.useScrollDirectionwatches the page’s vertical scroll alone, never a scrolling element inside it.useBroadcastChannelkeeps nothing posted before it joins or whilenameisnull, and a tab opened later receives none of the earlier messages.usePollingnever retries after a failure on its own, and does not pause while the tab is hidden.- A resource never loads again on its own. Only
refreshloads a key again, and a rejected key stays rejected until then.