@k8ordo/effects

React hooks that sync with the browser, tabs and timers without useEffect

bash
npm install @k8ordo/effects
src/components/header.tsx
'use client';

import { useOnline, useScrollDirection } from '@k8ordo/effects';

export function Header() {
  const online = useOnline();
  const hidden = useScrollDirection({ threshold: 64 }) === 'down';

  return (
    <header data-hidden={hidden}>
      {online ? null : <p>You are offline.</p>}
    </header>
  );
}

Hooks named for what they sync with

useWindowEvent syncs with window’s events, and useDocumentEvent with document’s. There is no useMount or the like, which would be a useEffect under another name.

There is no dependency array. A handler is the latest render’s when it runs, so it reads the current draft.

presenter.tsx
useWindowEvent('keydown', (event) => {
  if (event.key === 'Escape') setPresenting(false);
});

useDocumentEvent('visibilitychange', () => {
  if (document.visibilityState === 'hidden') save(draft);
});

Values that hydrate without a mismatch

A value hook returns the server’s value on the server and in the hydration render. The browser’s value comes from the render right after.

A subtree that calls useResource renders in the browser alone. The server writes the <Suspense> fallback into its HTML.

src/components/offline-notice.tsx
'use client';

import { useOnline } from '@k8ordo/effects';

export function OfflineNotice() {
  const online = useOnline();
  return online ? null : <p role="status">You are offline.</p>;
}

Sync that stops with the component

Listeners, channels, timers and polls start when the component mounts and stop when it unmounts.

On unmount, or when the key changes, a poll in flight is aborted through the signal it received.

thread-status.tsx
usePolling(threadId, async (id, signal) => {
  const response = await fetch(`/api/threads/${id}`, { signal });
  const thread = await parseThread(response);
  if (thread.status === 'running') return 2000;
  onSettled(thread);
  return null;
});