TypeScript React Hooks: State, Effects, and Refs


TypeScript does not change React’s hook rules, rendering model, or asynchronous behaviour. It does make the state and API boundaries of a hook visible—if we let it. The practical aim is not to annotate every generic. It is to make a component’s valid states, side-effect ownership, and reusable hook contracts obvious to the next person reading the code.
Hooks are especially good at hiding complexity behind a tidy function call. That is a strength until a hook returns a vague bag of booleans, a nullable value is asserted away, or an effect quietly races against a later render. The patterns below keep type information aligned with the runtime lifecycle rather than using types as a coat of paint.
Let State Inference Do Useful Work
When an initial value fully describes state, let TypeScript infer it. The inferred type is shorter and usually more precise than a manual annotation.
const [isOpen, setIsOpen] = useState(false);
const [filters, setFilters] = useState({ query: "", includeArchived: false });isOpen is boolean; filters has the object shape the component started with. Type an initial state explicitly when it is intentionally wider than the first value. The common example is data that begins absent:
type User = { id: string; name: string };
const [user, setUser] = useState<User | null>(null);Without <User | null>, useState(null) infers only null, making a later setUser(userFromApi) an error. That error is useful: it reveals that the initial value did not carry enough information to describe the future state.
Avoid solving that problem with as User. A cast claims a user already exists when the UI still has to handle loading, absence, and failure. Make the absence part of the state model instead.
const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set());The function form is useful for a non-trivial initial value; React calls it only for initialization. More importantly, the generic says exactly what the empty collection will later contain.
Model State Transitions, Not Just Values
Several related booleans often describe a state machine in disguise. isLoading, error, and data can produce contradictory combinations: loaded data plus an error, or neither data nor loading with no explanation. A discriminated union gives both render code and event handlers a coherent vocabulary.
type RemoteData<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; message: string };
const [profile, setProfile] = useState<RemoteData<User>>({ status: "idle" });Rendering narrows naturally:
switch (profile.status) {
case "success":
return <ProfileCard user={profile.data} />;
case "error":
return <p role="alert">{profile.message}</p>;
case "loading":
return <Spinner label="Loading profile" />;
default:
return <button onClick={loadProfile}>Load profile</button>;
}For a state machine with many transitions, reach for useReducer. A reducer makes the event and state vocabulary explicit, and its action union becomes a compact specification of what can change.
type EditorAction =
| { type: "changed"; value: string }
| { type: "saved"; revision: number }
| { type: "failed"; message: string };
function editorReducer(state: EditorState, action: EditorAction): EditorState {
switch (action.type) {
case "changed":
return { ...state, value: action.value, status: "dirty" };
case "saved":
return { ...state, status: "clean", revision: action.revision };
case "failed":
return { ...state, status: "error", message: action.message };
}
}The value is not the Reducer type itself. It is the forced decision: when a new event is added, which states can it reach and what should the UI do next?
Effects Need Lifecycles, Not Type Tricks
useEffect synchronizes a component with something outside React: a subscription, browser API, timer, network request, or imperative library. It is not a general place for “code after render.” Before writing one, name the external system and the cleanup it needs.
useEffect(() => {
const controller = new AbortController();
async function load() {
setProfile({ status: "loading" });
const response = await fetch(`/api/users/${userId}`, {
signal: controller.signal,
});
if (!response.ok) throw new Error("Profile request failed");
setProfile({ status: "success", data: (await response.json()) as User });
}
void load().catch((error: unknown) => {
if (!controller.signal.aborted) {
setProfile({
status: "error",
message: error instanceof Error ? error.message : "Unknown error",
});
}
});
return () => controller.abort();
}, [userId]);The effect callback itself should not be async: React expects either nothing or a cleanup function, not a promise. The inner async function leaves that contract intact. The abort controller is not merely a TypeScript detail; it prevents an earlier request from winning after the userId has changed.
Dependencies Are a Correctness Contract
A dependency list describes values an effect reads from the render that created it. Do not silence the hook linter to make a stale closure disappear. Restructure the code, move stable work outside the component, or make the intended dependency explicit.
TypeScript cannot prove a dependency list is complete or a response belongs to the current screen. Runtime design still matters: cleanup subscriptions, cancel requests where possible, and test rapid prop changes or unmounts.
Use Refs for Stable Identity
A ref stores a value across renders without causing a re-render when it changes. Use it for imperative element access, timer handles, previous values, or an instance owned by the component—not for state the UI should display.
const inputRef = useRef<HTMLInputElement>(null);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
function focusSearch() {
inputRef.current?.focus();
}The nullable initial value is honest: before React attaches the element, there is no input. Optional chaining preserves that lifecycle rather than asserting current!. For a browser timer, ReturnType<typeof setTimeout> avoids assuming a particular runtime’s numeric timer ID.
Refs also help an effect talk to an imperative integration while keeping rendering declarative. Create a map widget, chart, or socket once in a ref; update it in carefully scoped effects; destroy it in cleanup. If changing the value should change visible output, it belongs in state instead.
Build Custom Hooks as Small Contracts
A custom hook should expose a domain-level interface, not every implementation variable it happens to use. Give the caller actions and state they can understand, preserve inference where values are generic, and avoid returning an unlabelled tuple once there are more than two related values.
type Toggle = {
enabled: boolean;
enable(): void;
disable(): void;
toggle(): void;
};
export function useToggle(initial = false): Toggle {
const [enabled, setEnabled] = useState(initial);
return {
enabled,
enable: () => setEnabled(true),
disable: () => setEnabled(false),
toggle: () => setEnabled((current) => !current),
};
}Use the updater form when the next state depends on the previous state. It is robust across batching and frees the callback from a captured enabled value. A generic hook can similarly preserve its caller’s types:
export function useSelection<Item>(
items: readonly Item[],
getKey: (item: Item) => string
) {
const [selectedKey, setSelectedKey] = useState<string | null>(null);
const selected = items.find((item) => getKey(item) === selectedKey) ?? null;
return {
selected,
select: setSelectedKey,
clear: () => setSelectedKey(null),
};
}The hook returns Item | null, inferred from the caller’s array. It does not pretend it can validate arbitrary server data; parse that at the boundary before it enters the hook.
Keep asynchronous hooks honest
The hardest custom hooks often coordinate an asynchronous resource. Resist returning a promise from a hook and asking callers to manage its lifecycle themselves. Return the current state plus an explicit action, and decide what a second invocation means while the first is pending.
type SaveState =
| { status: "idle" }
| { status: "saving" }
| { status: "saved"; savedAt: Date }
| { status: "error"; message: string };
function useSaveDraft(save: (body: string) => Promise<void>) {
const [state, setState] = useState<SaveState>({ status: "idle" });
const submit = async (body: string) => {
setState({ status: "saving" });
try {
await save(body);
setState({ status: "saved", savedAt: new Date() });
} catch (error) {
setState({
status: "error",
message:
error instanceof Error ? error.message : "Could not save draft",
});
}
};
return { state, submit };
}This is still only a component-level contract. Whether writes are idempotent, whether a stale save may overwrite a later one, and how an offline retry works are product and server concerns. The hook should make those decisions visible in its name and returned states rather than quietly swallowing them.
Prefer fewer effects
Many effects are unnecessary because the value can be calculated while rendering or inside an event handler. If fullName is derived from firstName and lastName, calculate it; do not store it and synchronize it in an effect. If a button click should send analytics, send it in the click handler; it is already the event that owns the side effect.
This matters for typing because redundant state and effects manufacture more nullable values, dependency arrays, and timing paths than the feature actually needs. A smaller state model gives TypeScript a narrower, more useful universe of possibilities.
When an effect is genuinely necessary, write down its ownership in a sentence: “This component subscribes to the current room and unsubscribes when the room changes.” If that sentence is difficult to write, the effect likely combines two responsibilities and should be split. Separate effects can have separate dependency lists and cleanup functions, which is safer than one large effect guarded by conditionals.
Test behaviour at the hook boundary
Tests should prove the contract a component consumes: calling toggle changes enabled; cancelling an effect prevents an outdated result from rendering; a reducer refuses no impossible state. Do not write tests merely to confirm TypeScript accepts a type. Use type-level tests sparingly when generic inference is a public promise, and runtime tests for lifecycle, accessibility, and recovery.
Key Takeaways
- Let
useStateinfer types from complete initial values; write a generic when the initial value intentionally omits future possibilities. - Use discriminated unions and reducers when several values describe a real state machine.
- Treat effects as synchronization with an external system, with dependencies and cleanup designed at runtime.
- Use refs for stable imperative identity, not display state.
- Export custom hooks as small domain contracts that preserve inference and make their nullable states explicit.
Next, we return to Next.js forms: how to pair native HTML, server validation, Server Actions, status feedback, and progressive enhancement without creating a fragile client-only mutation layer.