Async state: one value, not three states
Managing async fetches with separate loading, error, and data states inside useEffect lets stale responses overwrite newer selections (react-async-race) and lets those three states drift out of sync (react-split-state).
In short
- One state value: use
useTaskfrom@evobug_com/safe-ts-react/taskto store oneAsyncState<T, E>(Idle,Loading,Ready,Failed). - Automatic abort: every
run(...)cancels the previousAbortSignal, and unmount aborts in-flight requests. - React 19
use()safety: pass stable/cached promises rather than creating a new promise every render (react-uncached-promise).
In the examples below, fetchUser(id, signal) returns Promise<Result<User, ApiError>>:
✕ Rejectedreact-async-racereact-split-state
tsx
import { useEffect, useState } from "react";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fetchUser, type User } from "./api";
export function Profile({ id }: { id: string }) {
const [loading, setLoading] = useState(false);
const [failed, setFailed] = useState("");
const [user, setUser] = useState<User>();
useEffect(() => {
const load = async (): Promise<void> => {
setLoading(true);
const result = await fetchUser(id);
setLoading(false);
if (isErr(result)) setFailed(result.error.message);
else setUser(result);
};
void load();
}, [id]);
if (loading) return <p>Loading…</p>;
if (failed !== "") return <p>{failed}</p>;
return <p>{user?.name}</p>;
}useTask from @evobug_com/safe-ts-react/task runs the work and keeps where it stands in one AsyncState value: Idle, Loading, Ready with a value, or Failed with an error. Each run(...) aborts the previous one (its signal fires), so only the latest response is shown, and the run in progress is aborted when the component unmounts. That holds for what the callback returns; what it writes itself after an await (a ref, a store) still lands from a superseded run (superseded-task-write). run is the same function on every render, so it can go in the effect's dependencies:
✓ Accepted0 diagnostics
tsx
import { useEffect } from "react";
import { Match } from "@evobug_com/safe-ts-react/match";
import { useTask } from "@evobug_com/safe-ts-react/task";
import { fetchUser } from "./api";
export function Profile({ id }: { id: string }) {
const { state, run } = useTask((signal, id: string) => fetchUser(id, signal));
useEffect(() => {
run(id).catch((reason: unknown) => console.error(reason));
}, [id, run]);
return (
<Match
on={state}
Loading={() => <p>Loading…</p>}
Ready={({ value }) => <p>{value.name}</p>}
Failed={({ error }) => <p>Couldn't load the user: {error.message}</p>}
_={() => undefined}
/>
);
}<Match> gets a function per variant, given that variant's fields: in Ready={({ value }) => ...}, value is the User, never undefined. _ covers every variant without a function of its own (here Idle). TypeScript checks the props: without _, a missing variant is a type error, so a variant added to the enum later is too.
run(id) rejects only when the work itself threw or rejected instead of returning an Err: a bug, which useTask doesn't turn into Failed (that holds an ApiError, and a thrown value can be anything). Log it, as above.
When every variant shows the same element, compute what it shows with match from @evobug_com/safe-ts-std/enum instead:
✓ Accepted0 diagnostics
tsx
import { useEffect } from "react";
import { match } from "@evobug_com/safe-ts-std/enum";
import { useTask } from "@evobug_com/safe-ts-react/task";
import { fetchUser } from "./api";
export function Status({ id }: { id: string }) {
const user = useTask((signal, id: string) => fetchUser(id, signal));
const { run } = user;
useEffect(() => {
run(id).catch((reason: unknown) => console.error(reason));
}, [id, run]);
const status: string = match(user.state, {
Idle: () => "",
Loading: () => "Loading…",
Ready: ({ value }) => value.name,
Failed: ({ error }) => `Couldn't load the user: ${error.message}`,
});
return <p>{status}</p>;
}tsx
import { useEffect } from "react";
import { unreachable as __matchUnreachable } from "@evobug_com/safe-ts-std/enum"; import { match } from "@evobug_com/safe-ts-std/enum";
import { useTask } from "@evobug_com/safe-ts-react/task";
import { fetchUser } from "./api";
export function Status({ id }: { id: string }) {
const user = useTask((signal, id: string) => fetchUser(id, signal));
const { run } = user;
useEffect(() => {
run(id).catch((reason: unknown) => console.error(reason));
}, [id, run]);
const __ms1 = user.state; let __mv1: string; switch (__ms1.tag) {
case "Idle": { __mv1 = ""; break; }
case "Loading": { __mv1 = "Loading…"; break; }
case "Ready": { const { value } = __ms1; __mv1 = value.name; break; }
case "Failed": { const { error } = __ms1; __mv1 = `Couldn't load the user: ${error.message}`; break; } default: __mv1 = __matchUnreachable(__ms1); } const status: string = __mv1;
return <p>{status}</p>;
}Without useTask
An effect that loads data by hand must stop the run it no longer needs: return a cleanup that aborts the request (or sets an ignore flag the run checks before setting state):
✅ Also accepted: an effect that loads by hand, where useTask can't be used
✓ Accepted0 diagnostics
tsx
import { useEffect, useState } from "react";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fetchUser, type User } from "./api";
export function Name({ id }: { id: string }) {
const [user, setUser] = useState<User>();
useEffect(() => {
const controller = new AbortController();
const load = async (): Promise<void> => {
const result = await fetchUser(id, controller.signal);
if (!controller.signal.aborted && !isErr(result)) setUser(result);
};
void load();
return () => controller.abort();
}, [id]);
return <p>{user?.name ?? "…"}</p>;
}The three states of the first example are reported on their own too (react-split-state): a loading state turned on before an await and off after it, next to other states set after it.
use needs a promise that lasts
React 19's use(promise) suspends until the promise settles, and renders again. A promise made during render is a new one on that next render, so it never settles (react-uncached-promise):
✕ Rejectedreact-uncached-promise
tsx
import { use } from "react";
type User = { readonly name: string };
async function loadUser(id: string): Promise<User> {
return { name: id };
}
export function Name({ id }: { id: string }) {
const user = use(loadUser(id));
return <p>{user.name}</p>;
}✅ Accepted: the promise comes from outside the render
✓ Accepted0 diagnostics
tsx
import { use } from "react";
type User = { readonly name: string };
export function Name({ user }: { user: Promise<User> }) {
return <p>{use(user).name}</p>;
}Make it once, where it is requested (a route loader, an event handler, a parent), or keep it in a cache keyed by its arguments, and pass it down. Wrap the component in <Suspense> for the wait and an error boundary for a rejection: use throws what the promise rejects with.
Rules on this page: react-async-race, react-split-state, react-uncached-promise