Full answer
TypeScript can infer most of this. You add annotations where the initial value does not tell the whole story.
useState: useState(0) is a number state. useState<User | null>(null) is needed because null alone would infer the type null. For an empty array, write useState<string[]>([]).
useRef has two shapes. For a DOM node, useRef<HTMLInputElement>(null) returns a ref object whose current is HTMLInputElement | null, so check for null before use or use optional chaining. For a mutable value, useRef<number>(0) gives a box you can write to.
useReducer: describe actions as a discriminated union, a set of object types distinguished by a literal type field:
type Action = { type: 'added'; name: string } | { type: 'removed'; id: number }.
Inside the reducer, a switch on action.type narrows the type, so action.name is only available in the added case. Add a never check in the default branch so a new action that is not handled becomes a compile error. dispatch is typed Dispatch<Action>.
Context: createContext<Value | null>(null) avoids a fake default value. A custom hook calls useContext and throws if it is null, which narrows the result to Value for every caller.
Event handlers and custom hooks follow the same ideas. Return tuples with as const or declare the return type so the tuple is not widened to an array.
Types do not exist at runtime, so validate data that comes from outside the app.
import { createContext, useContext, useReducer, useRef, useState, type Dispatch, type ReactNode } from 'react';
type Student = { id: number; name: string };
type Action = { type: 'added'; name: string } | { type: 'removed'; id: number };
function rosterReducer(state: Student[], action: Action): Student[] {
switch (action.type) {
case 'added':
return [...state, { id: state.length + 1, name: action.name }];
case 'removed':
return state.filter((s) => s.id !== action.id);
default: {
const unreachable: never = action;
throw new Error('Unhandled action: ' + JSON.stringify(unreachable));
}
}
}
type RosterContextValue = { students: Student[]; dispatch: Dispatch<Action> };
const RosterContext = createContext<RosterContextValue | null>(null);
function RosterProvider({ children }: { children: ReactNode }) {
const [students, dispatch] = useReducer(rosterReducer, []);
return <RosterContext value={{ students, dispatch }}>{children}</RosterContext>;
}
function useRoster(): RosterContextValue {
const value = useContext(RosterContext);
if (value === null) throw new Error('useRoster must be used inside RosterProvider');
return value;
}
function RosterEditor() {
const { students, dispatch } = useRoster();
const inputRef = useRef<HTMLInputElement>(null);
const [selected, setSelected] = useState<Student | null>(null);
function add() {
const name = inputRef.current?.value.trim();
if (name) dispatch({ type: 'added', name });
}
return (
<div>
<input ref={inputRef} defaultValue="Asha" />
<button onClick={add}>Add student</button>
<ul>
{students.map((s) => (
<li key={s.id}>
<button onClick={() => setSelected(s)}>{s.name}</button>
</li>
))}
</ul>
<p>Selected: {selected ? selected.name : 'none'}</p>
</div>
);
}
export default function App() {
return (
<RosterProvider>
<RosterEditor />
</RosterProvider>
);
}The file passed the TypeScript compiler in strict mode and ran after the types were removed. The check pressed Add student and then the new name. Rendered result: <div><input value="Asha"><button>Add student</button><ul><li><button>Asha</button></li></ul><p>Selected: Asha</p></div>
Key points
- Add a generic to useState only when the initial value is null or empty.
- DOM refs are useRef<HTMLElement>(null) and current may be null.
- Model reducer actions as a discriminated union and check exhaustiveness with never.
- Type context as Value | null and add a hook that narrows it.
- Use as const or an explicit return type for tuple-returning hooks.
Common mistakes
- Writing useState(null) and then assigning an object, which fails to type check.
- Forgetting that a DOM ref's current may be null.
- Using string for the action type instead of literal types, which loses narrowing.
- Giving the context a fake default object so a missing provider goes unnoticed.
- Using the non-null assertion operator to silence errors that point to real bugs.
Follow-ups
- What is exhaustiveness checking and why is it useful in reducers?
- How would you type a custom hook that returns a tuple?
- How do you derive TypeScript types from a runtime schema?
Tips
- Show the discriminated union. It is the most useful TypeScript idea in React code.
- Explain the null-context pattern in one sentence.
- Mention that types do not validate runtime data.