React 19 にuseState + useEffect でuse() に
Before: useState + useEffect を毎回書いていた
React 18 以前、
function UserProfile({ id }: { id: string }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
setLoading(true);
fetchUser(id)
.then(setUser)
.catch(setError)
.finally(() => setLoading(false));
}, [id]);
if (loading) return <Spinner />;
if (error) return <p>エラー: {error.message}</p>;
return <div>{user?.name}</div>;
}
ステート 3 本、useEffect 1 本で 20 行超。
After: use() に渡すだけ
React 19 の use() フックは Promise をSuspense と ErrorBoundary に
// 親: Promise を useMemo で作って渡す
function UserPage({ id }: { id: string }) {
const userPromise = useMemo(() => fetchUser(id), [id]);
return (
<Suspense fallback={<Spinner />}>
<ErrorBoundary fallback={<p>データを取得できませんでした</p>}>
<UserProfile promise={userPromise} />
</ErrorBoundary>
</Suspense>
);
}
// 子: use() で受け取るだけ
function UserProfile({ promise }: { promise: Promise<User> }) {
const user = use(promise);
return <div>{user.name}</div>;
}
UserProfile がid がuseMemo がSuspense が
条件分岐の中で呼べるのが他のフックと違う
React のuse() はその
function MaybeProfile({
show,
promise,
}: {
show: boolean;
promise: Promise<User>;
}) {
if (!show) return <p>非表示</p>;
const user = use(promise); // ← if の中でも呼べる
return <div>{user.name}</div>;
}
フィーチャーフラグで
やらかし: ErrorBoundary なしで動かしたら画面が白くなった
最初にSuspense だけErrorBoundary を
// ❌ ErrorBoundary を忘れたパターン
<Suspense fallback={<Spinner />}>
<UserProfile promise={userPromise} />
</Suspense>
API が 500 をuse() はSuspense はそれをSuspense と ErrorBoundary は
React は ErrorBoundary を
npm install react-error-boundary
import { ErrorBoundary } from "react-error-boundary";
<Suspense fallback={<Spinner />}>
<ErrorBoundary fallbackRender={({ error }) => <p>{error.message}</p>}>
<UserProfile promise={userPromise} />
</ErrorBoundary>
</Suspense>
まとめ
- loading・
error 管理は SuspenseとErrorBoundaryに任せ、 コンポーネントは データを 使うことだけに 集中できる - 条件分岐の
中で 呼べるのが 他の フックとの 唯一の 違い ErrorBoundaryなしで使うと reject 時に ツリーが クラッシュする
掲載時点use は
詳細は React 19 公式