React and TypeScript work best together when component boundaries describe the data and browser interactions they actually support. This guide provides reusable patterns for typing props, children, events, refs, state, custom hooks, context, and controlled forms without falling back to any or adding generics that make components harder to use.
Overview
A practical React TypeScript setup starts with a simple rule: infer types when the implementation makes them obvious, and write explicit types at public boundaries. A component's props, a hook's return value, and a context value are boundaries because other code depends on them. Clear boundaries make editor completion more useful and help the compiler identify mismatched data before it reaches the browser.
The examples below use function components and modern React conventions. They are intended as patterns rather than a single application architecture. You can apply them in a standard React application, a framework project such as Next.js, or a component library, provided the project's React and TypeScript versions support the syntax used by your codebase.
For the compiler settings behind these examples, see the TypeScript tsconfig guide to strict compiler options. Strict settings tend to expose missing states and unsafe assumptions early, which is particularly useful when components receive data from APIs or user input.
Core concepts
Typing component props
Use a type or interface to describe the values a component accepts. The choice between type and interface is usually less important than naming the boundary clearly and keeping it focused.
type UserCardProps = {
name: string;
role?: string;
onSelect: (name: string) => void;
};
function UserCard({ name, role = "Member", onSelect }: UserCardProps) {
return (
<button type="button" onClick={() => onSelect(name)}>
<strong>{name}</strong>
<span>{role}</span>
</button>
);
}
Optional properties should represent genuinely optional input. A default value such as role = "Member" keeps the rendered component predictable while allowing callers to omit that prop. Callback types should describe the information the component sends, not the implementation details of the callback.
Children and composition
For ordinary nested JSX, ReactNode is a flexible choice because it includes strings, elements, fragments, and other renderable values.
import type { ReactNode } from "react";
type PanelProps = {
title: string;
children: ReactNode;
};
function Panel({ title, children }: PanelProps) {
return (
<section>
<h2>{title}</h2>
<div>{children}</div>
</section>
);
}
Use a narrower type only when the component requires a specific shape. For example, a component that must receive exactly one particular element may need a more constrained contract, but most layout components should not impose that complexity.
Events: type the element interaction
React event types are generic over the element involved. Letting TypeScript infer an inline handler is often the simplest approach:
function SearchBox() {
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
console.log(event.currentTarget.value);
};
return <input type="search" onChange={handleChange} />;
}
Common event types include React.ChangeEvent<HTMLInputElement> for inputs, React.FormEvent<HTMLFormElement> for form submission, React.MouseEvent<HTMLButtonElement> for button clicks, and React.KeyboardEvent<HTMLInputElement> for keyboard interactions. Prefer currentTarget when you need the element the handler is attached to. The broader target property may refer to a nested element.
State and type narrowing
Type inference works well for simple state:
const [isOpen, setIsOpen] = useState(false);
const [query, setQuery] = useState("");
Provide a type when the initial value does not express the full state, especially for nullable data or arrays:
type User = { id: string; name: string };
const [selectedUser, setSelectedUser] = useState<User | null>(null);
const [users, setUsers] = useState<User[]>([]);
if (selectedUser) {
console.log(selectedUser.name);
}
The conditional check narrows User | null to User. Avoid using a non-null assertion such as selectedUser!.name unless the invariant is both real and difficult to express another way. For more examples of narrowing and compiler messages, see the TypeScript error fixes guide.
Refs
Use useRef with a nullable element type when React will assign a DOM node after rendering:
const inputRef = useRef<HTMLInputElement | null>(null);
function focusInput() {
inputRef.current?.focus();
}
return <input ref={inputRef} />;
The optional chaining reflects the lifecycle: the element may not exist during the first render or after unmounting. For a mutable value that does not refer to a DOM node, initialize the ref with the value's type and use it as an instance-like container.
Custom hooks
A custom hook should expose a small, intentional API. Explicitly typing its return value is useful when the returned object has several fields or when the hook is shared across files.
type UseToggleResult = {
enabled: boolean;
toggle: () => void;
setEnabled: (value: boolean) => void;
};
function useToggle(initial = false): UseToggleResult {
const [enabled, setEnabled] = useState(initial);
const toggle = () => setEnabled(value => !value);
return { enabled, toggle, setEnabled };
}
Do not add a generic merely because a hook could theoretically support many types. A generic is worthwhile when the caller's type changes the hook's behavior or output, such as a reusable selection hook. Otherwise, a concrete type is easier to read and debug.
Context
Context values are commonly unavailable before a provider is mounted, so model that possibility or enforce provider usage with a custom hook.
type Theme = "light" | "dark";
type ThemeContextValue = {
theme: Theme;
setTheme: (theme: Theme) => void;
};
const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);
function useTheme() {
const context = useContext(ThemeContext);
if (!context) {
throw new Error("useTheme must be used within ThemeProvider");
}
return context;
}
This pattern prevents every consumer from handling an artificial undefined case while still making a missing provider visible during development.
Controlled forms
For a small form, model the fields as one object and type the change event for the input element:
type FormValues = {
email: string;
password: string;
};
function SignInForm() {
const [values, setValues] = useState<FormValues>({
email: "",
password: ""
});
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.currentTarget;
setValues(current => ({ ...current, [name]: value }));
};
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
// Validate values before sending them to an API.
};
return (
<form onSubmit={handleSubmit}>
<input name="email" value={values.email} onChange={handleChange} />
<input name="password" type="password" value={values.password} onChange={handleChange} />
<button type="submit">Sign in</button>
</form>
);
}
TypeScript checks the component's internal shape, but it does not validate arbitrary strings received from a user or server at runtime. For larger forms, schema validation and a form library can provide runtime checks as well as typed field values. The React Hook Form and Zod guide covers that approach.
Related terms
- Props
- Inputs passed from a parent component to a child component. Treat them as a public API and keep their shape deliberate.
- Controlled component
- A form element whose displayed value is driven by React state. The change handler updates that state.
- Uncontrolled component
- A form element that keeps its value in the DOM and is read through a ref or form submission. This can be useful when React does not need every keystroke.
- Type narrowing
- The process of proving to TypeScript that a union value is a more specific type, usually with a condition, switch, or custom type guard.
- Generic
- A type parameter that allows a function or component to preserve a relationship between input and output types. Use it when that relationship matters to callers.
Practical use cases
Use these patterns as a decision guide while building components:
- Reusable buttons and cards: Define explicit props and callback payloads. Use string unions for constrained variants such as
"primary" | "secondary". - Search and filter controls: Type input events at the boundary, then store normalized values in state. Keep parsing and validation separate from rendering.
- Data-loading screens: Represent loading, success, and failure as distinct states rather than assuming fetched data is always present. A discriminated union can make impossible UI states harder to express.
- Design-system components: Start with the smallest stable prop contract. Add polymorphic or generic patterns only when repeated usage demonstrates a real need.
- Forms with server submission: Define a form value type, prevent the default submit behavior, validate at runtime, and model server errors separately from field values.
When a compiler error appears, first check whether the component contract is accurate. Many errors are symptoms of a missing state, an overly broad prop, or a value that has not been narrowed. If the issue involves configuration rather than component code, consult the complete tsconfig.json guide before weakening a type with an assertion.
When to revisit
Revisit this reference when your React or TypeScript versions change, when a framework updates its JSX or event typings, or when a component is promoted from local code into a shared library. Supporting examples may also need review when your form library, validation approach, or build configuration changes.
As a practical maintenance pass, inspect every new any, non-null assertion, and type cast. Confirm that it represents a known boundary rather than hiding an uncertain value. Check whether shared props still describe actual usage, whether context consumers have a clear provider requirement, and whether controlled forms validate values before network submission.
To apply the guide, choose one component with unclear types, write its props first, type its event handlers at the DOM boundary, model nullable state explicitly, and run the project with strict checking enabled. Then extract a custom hook or shared type only after the repeated shape is clear. This keeps the codebase safe without turning every React component into a complex type-level exercise.