State & reducers; Context typing
Manage component state with useState and useReducer, then lift state into a typed Context with a safe custom hook.
Intro
Goal: Start with local state (useState), move to a typed reducer (useReducer), then lift state to a typed Context with a safe custom hook.
- Model state and actions explicitly
- Prefer discriminated unions
- Guard Context access
useState typed
Annotate state with a concrete type (e.g., number). Use the updater form to avoid stale closures in rapid updates.
import React, { useState } from "react"
export default function Counter() {
const [count, setCount] = useState<number>(0)
const inc = () => setCount(c => c + 1)
const dec = () => setCount(c => c - 1)
return (
<div style={{ display: "grid", gap: 8 }}>
<div>Count: {count}</div>
<div style={{ display: "flex", gap: 8 }}>
<button onClick={inc}>+1</button>
<button onClick={dec}>-1</button>
</div>
</div>
)
}All lessons in this course
- Props & children; event handlers; refs
- State & reducers; Context typing
- Component generics — intro