@k8ordo/effects

useEffectを書かずにブラウザやタブ、タイマーと同期するReactのフック集

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>
  );
}

同期する相手の名前を持つフック

useWindowEventはwindowのイベントと、useDocumentEventはdocumentのイベントと同期します。名前を変えただけのuseEffectになるuseMountのようなフックはありません。

依存配列は書きません。ハンドラは呼ばれる時点で最新の描画のものになるので、いまのdraftを読めます。

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

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

ハイドレーションで食い違わない値

値を返すフックは、サーバーとハイドレーションの描画ではサーバーの値を返します。ブラウザの値を返すのは、そのすぐあとの描画からです。

useResourceを使うサブツリーは、ブラウザだけで描画されます。サーバーは<Suspense>のfallbackを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>;
}

コンポーネントと一緒に止まる同期

リスナーとチャンネル、タイマー、ポーリングはコンポーネントのマウントで始まります。アンマウントすると、どれも止まります。

アンマウントやキーの変更があると、実行中のpollは受け取ったsignalで中断されます。

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;
});