Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.3 — Typing State, Refs and Reducers
React · Example 1 of 3

useState: inferred, null until loaded, and a typed empty array

The first render shows the loading state, because user is null. After the fake request, user is a User and the early return no longer runs. setTags((t) => [...t, ...]) type-checks because t is string[]; with useState([]) it would be never[] and the same line would be an error.

Let useState infer simple types, but give it a type argument when the start value is null or an empty array; type DOM refs as useRef<HTMLInputElement>(null); and type reducer actions as a discriminated union so a switch with a never check proves every action is handled.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a Counter reducer with actions { type: "increment" }, { type: "decrement" } and { type: "set"; value: number }, with an exhaustive never check, and buttons for each.

02

Write a component with useState<"idle" | "loading" | "done">("idle") and a button that goes to loading, then to done after a 300 ms fake request. Show the status and log each change.

Explain it without notes

01

When does useState need a type argument, and what goes wrong without one?

02

How do you type a ref to an input, and why is current possibly null?

03

What is a discriminated union, and why is it a good fit for reducer actions?

04

How does the never trick make a switch exhaustive?

useState: inferred, null until loaded, and a typed empty array

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render: loading
render: Asha likes 0 tags []
render: Asha likes 1 tags []
render: Asha likes 1 tags [ 'tag1' ]