All topics
Advancedintermediate

TypeScript with React: Typing Props, State, and Hooks

Learn the common TypeScript patterns for typing function components, props, hooks, and event handlers in React.

Typing a function component's props is typically done with an interface or type alias describing the shape of the props object, referenced as the parameter type: function Button(props: ButtonProps), or destructured directly with an inline annotation. Optional props use ?, and a children prop (when a component needs to accept nested JSX) is typed as React.ReactNode, which covers strings, numbers, elements, fragments, and arrays of these — the full range of what's actually valid to render.

Typing React components is like giving a shipping label a strict, checkable format before the package (props) ever leaves the warehouse — if the label's fields don't match what's required (a missing required prop, a wrong data type), the mistake gets caught at the loading dock (compile time) instead of causing confusion when the package arrives somewhere unexpected (a runtime bug).

Key Concepts

1
useState's generic type parameter is usually inferred correctly from the initial value (useState(0) infers number), but needs to be explicit when the initial value doesn't fully capture the eventual type, most commonly useState<User | null>(null), since inferring from null alone would incorrectly type the state as always null.
useStateuseState(0)numberuseState<User | null>(null)null
2
Event handler parameters need React's specific synthetic event types rather than plain DOM event types, since the object your handler receives is a SyntheticEvent, not a native one — React.ChangeEvent<HTMLInputElement> for an input's onChange, React.MouseEvent<HTMLButtonElement> for a button's onClick, and so on, each parameterized by the specific element type to correctly type event.target and its properties.
SyntheticEventReact.ChangeEvent<HTMLInputElement>React.MouseEvent<HTMLButtonElement>event.target
3
Interviewers assessing TypeScript+React fluency ask candidates to properly type a form component's props (including an optional callback prop and a children slot) and its onChange/onSubmit handlers, checking for correct use of generic event types and appropriate use of union types (like string | null) for state that starts as empty/absent before being populated.
onChangeonSubmitstring | null