Typing props, state, and hooks with TypeScript
Typing component props, children, useState, and useReducer in React, plus writing a generic custom hook. Assumes TypeScript basics.
Typing props, state, and hooks with TypeScript
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A component's props are typed with an interface or type alias, and children should be typed as React.ReactNode rather than string or JSX.Element, because a component can receive text, elements, arrays of elements, or nothing at all as children.
- useState almost always infers its type correctly from the initial value you pass it, and you only need an explicit type argument when the state's type is wider than what the initial value alone implies, such as a value that starts null but can later become an object.
- useReducer's state and action types are usually worth defining explicitly as a union of action objects, because the reducer function's switch statement then gets exhaustiveness checking from the compiler.
- A generic custom hook lets the hook's return type adapt to whatever type its caller passes in, which plain union types cannot do as precisely.
- TypeScript's own generics, interfaces, and union types are assumed knowledge here; this lesson only covers where those general features show up in React-shaped code.
- Getting these annotations right pays off most at the boundary between components, where a prop typo or a missing field becomes a compile error instead of an undefined crash in the browser.
What this lesson assumes
This lesson assumes you already know TypeScript’s own type system — interfaces, generics, union types, narrowing. If any of that is shaky, the typescript roadmap covers it from the ground up. What’s left to learn here is specifically how those features show up when you apply them to React’s component model and hooks, which is a narrower and more concrete question.
Typing props and children
A component’s props are an ordinary object type, almost always written as an interface:
interface ButtonProps {
label: string;
onClick: () => void;
variant?: "primary" | "danger";
children?: React.ReactNode;
}
function Button({ label, onClick, variant = "primary", children }: ButtonProps) {
return (
<button className={variant} onClick={onClick}>
{label}
{children}
</button>
);
}
children is the one prop worth calling out specifically. It’s tempting to type it as JSX.Element, but that only covers a single React element — it rejects a plain string, a number, an array of elements, or null, all of which are legal children. React.ReactNode is the union that actually covers everything React can render as children, which is why it’s the standard choice.
Typing useState
Most of the time, useState needs no annotation at all:
const [count, setCount] = useState(0); // inferred as number
const [name, setName] = useState(""); // inferred as string
The type argument becomes necessary when the state’s eventual type is wider than its initial value alone implies — most commonly, state that starts out empty or absent and is filled in later:
interface User {
id: string;
name: string;
}
// Without the type argument, TypeScript infers `null` as the only type,
// and a later setUser({ id, name }) would be a compile error.
const [user, setUser] = useState<User | null>(null);
The rule of thumb: let inference run when the initial value already fully describes the type; reach for the explicit useState<T>(...) form the moment the initial value is a placeholder for something richer that arrives later.
Typing useReducer
useReducer benefits from explicit types on both sides: the state shape, and the set of actions the reducer accepts.
interface CartState {
items: string[];
total: number;
}
type CartAction =
| { type: "add"; item: string; price: number }
| { type: "remove"; item: string }
| { type: "clear" };
function cartReducer(state: CartState, action: CartAction): CartState {
switch (action.type) {
case "add":
return { items: [...state.items, action.item], total: state.total + action.price };
case "remove":
return { ...state, items: state.items.filter((i) => i !== action.item) };
case "clear":
return { items: [], total: 0 };
}
}
Writing CartAction as a union of specific object shapes, each tagged by a literal type, is what makes the switch exhaustive and safe: inside the "add" case, TypeScript knows action.item and action.price exist, and if you add a new action variant later but forget a case, the compiler flags the unhandled branch rather than letting it fall through silently at runtime.
Generics in a custom hook
A custom hook that stores data of some caller-chosen type should be generic rather than locked to one concrete type:
function useLocalStorage<T>(key: string, initialValue: T) {
const [value, setValue] = useState<T>(() => {
const stored = localStorage.getItem(key);
return stored ? (JSON.parse(stored) as T) : initialValue;
});
useEffect(() => {
localStorage.setItem(key, JSON.stringify(value));
}, [key, value]);
return [value, setValue] as const;
}
const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "light");
const [user, setUser] = useLocalStorage<User | null>("user", null);
The type parameter T flows from the call site all the way through to the returned setter, so setTheme only accepts "light" | "dark" and setUser only accepts a User | null, with one hook definition serving both. Without the generic, you’d either write a separate hook per data shape or give up and type everything any.
What the video covers
Web Dev Simplified’s video is a tight six minutes on exactly one piece of this puzzle: generic components, where a component’s own prop types adapt to a type parameter the way the hook above does. It doesn’t touch props/children typing, useState, or useReducer at all, which is why this lesson’s prose carries those directly rather than leaning on the video for them.
Where this fits
This lesson sits late in the roadmap because it assumes both custom hooks and useReducer. Next: code-splitting and lazy loading.
Check yourself
Why is React.ReactNode the right type for a children prop instead of JSX.Element?
JSX.Element only covers a single element, but children can legally be a string, a number, an array of elements, a fragment, or nothing, and React.ReactNode is the union type that covers all of those possibilities.
When does useState need an explicit type argument instead of relying on inference from its initial value?
When the initial value's inferred type is narrower than the type the state will actually hold later, most commonly when state starts as null but will be set to some object type after an async call resolves, such as useState<User | null>(null).
What does typing useReducer's action parameter as a union of specific action objects buy you that a loosely typed action object does not?
It makes the compiler check that every case in the reducer's switch statement is handled and that each case only destructures the fields that action type actually has, catching a missing case or a typo'd field name at compile time instead of at runtime.
What problem does making a custom hook generic solve that a hook typed with a fixed, concrete type cannot?
A generic hook's return type adapts to whatever type parameter the caller supplies, so one hook definition like useLocalStorage<T> works correctly and type-safely for a string, a number, or an object, instead of needing a separate hook or an unsafe any-typed version for each shape of data.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.