TypeScript with React: A Practical Guide to Props, Events, Hooks, and Component APIs
ReactTypeScriptcomponentspropshookseventsfrontend development

TypeScript with React: A Practical Guide to Props, Events, Hooks, and Component APIs

TTypeScript Website Editorial Team
2026-11-06
7 min read

A practical TypeScript with React guide to typing props, children, events, state, refs, forms, hooks, context, and component APIs.

Typing a React component well is less about adding annotations everywhere and more about designing a clear contract between the component and its callers. This practical TypeScript guide covers props, children, events, state, refs, forms, custom hooks, context, and polymorphic components, with reusable patterns you can apply when building or reviewing a React codebase.

Overview

A React component usually has three type boundaries: the values it receives, the values it manages, and the values it exposes through callbacks or refs. TypeScript is most useful when those boundaries describe the component's real behavior without making every caller repeat information that the compiler can infer.

Start with strict compiler settings and let TypeScript infer local values where the initial value makes the type obvious. Add explicit types at public boundaries, such as exported components, shared hooks, context values, and data returned from an API. This balance keeps component code readable while making accidental API changes visible during development.

A basic component API

type UserCardProps = {
  name: string;
  avatarUrl?: string;
  onSelect: (name: string) => void;
};

export function UserCard({ name, avatarUrl, onSelect }: UserCardProps) {
  return (
    <button type="button" onClick={() => onSelect(name)}>
      {avatarUrl && <img src={avatarUrl} alt="" />}
      <span>{name}</span>
    </button>
  );
}

This example makes required and optional values explicit, types the callback at the point where it is defined, and avoids accepting an open-ended object of unknown props. A focused prop type is easier to understand and harder to misuse.

Checklist by scenario

1. Typing props and children

  • Use a type or interface to describe the component's own props.
  • Mark a prop optional only when the component has a meaningful default or alternate behavior.
  • Type callback parameters and return values according to the component's contract.
  • Declare children deliberately instead of assuming every component should render arbitrary content.
import type { ReactNode } from "react";

type PanelProps = {
  title: string;
  children: ReactNode;
  footer?: ReactNode;
};

export function Panel({ title, children, footer }: PanelProps) {
  return (
    <section>
      <h2>{title}</h2>
      <div>{children}</div>
      {footer && <footer>{footer}</footer>}
    </section>
  );
}

Use ReactNode when a slot may contain text, elements, fragments, or other renderable values. Use a narrower type when the API requires a specific element shape. For example, a component that expects one action element should not silently accept any renderable child.

2. Typing DOM events

Event types should match the element and event handler. React's event types are generic, so the element type can be supplied when useful.

Use caseTypical typeExample handler
Text input changeReact.ChangeEvent<HTMLInputElement>(event) => setValue(event.currentTarget.value)
Form submissionReact.FormEvent<HTMLFormElement>(event) => { event.preventDefault(); }
Button clickReact.MouseEvent<HTMLButtonElement>(event) => handleClick(event)
Keyboard interactionReact.KeyboardEvent<HTMLElement>(event) => handleKey(event.key)
Focus changeReact.FocusEvent<HTMLInputElement>(event) => validate(event.currentTarget)
Select changeReact.ChangeEvent<HTMLSelectElement>(event) => setRole(event.currentTarget.value)

For inline handlers, contextual typing often removes the need for an annotation:

<input
  value={query}
  onChange={(event) => setQuery(event.currentTarget.value)}
/>

If a handler is passed as a prop, type the function in the prop definition. Prefer currentTarget when you mean the element whose handler is running; it is usually a better match for the declared element than a broadly typed target.

3. Typing state, refs, and forms

Let the initial state communicate its type when possible:

const [count, setCount] = useState(0);
const [status, setStatus] = useState<"idle" | "saving" | "error">("idle");
const [user, setUser] = useState<User | null>(null);

Use a union when a value has distinct states. This is more informative than using a string for every status or an empty object as a placeholder. For DOM refs, include the element type and initialize the ref with null:

const inputRef = useRef<HTMLInputElement | null>(null);

function focusInput() {
  inputRef.current?.focus();
}

For forms, type the submit event and validate values before treating them as domain data. TypeScript describes the shape your code expects; it does not validate arbitrary form or network input at runtime. A schema library can provide that runtime boundary when data comes from outside the component.

4. Typing custom hooks

A custom hook should expose a small, predictable result. An object is often easier to extend without changing the meaning of tuple positions:

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 };
}

When a hook returns a tuple, use a tuple return type or a const assertion if inference might widen the values into a general array. For generic hooks, place the type parameter where the relationship matters:

function useSelection<T>(items: T[], initial?: T) {
  const [selected, setSelected] = useState<T | undefined>(initial);
  return { items, selected, setSelected };
}

5. Typing context and component APIs

Do not create a context whose default value is a misleading empty object. A nullable context makes the missing provider an explicit case:

type ThemeContextValue = {
  mode: "light" | "dark";
  setMode: (mode: "light" | "dark") => void;
};

const ThemeContext = createContext<ThemeContextValue | null>(null);

export function useTheme() {
  const value = useContext(ThemeContext);
  if (!value) throw new Error("useTheme must be used within ThemeProvider");
  return value;
}

For a polymorphic component, keep the supported element choices constrained. A simple generic API can combine your own props with the selected element's native props, but pay attention to conflicts such as your color prop overriding a native attribute. If the abstraction requires complex overloads or frequent type assertions, a small set of explicit components may be clearer.

What to double-check

  • Inference: Hover over state, callback, and ref values in your editor. If a value is unexpectedly never, unknown, or a broad union, inspect the initializer and generic arguments first.
  • Prop boundaries: Check whether callers can pass values the component cannot use. Replace any, broad index signatures, and optional-everything props with a smaller contract.
  • Native element props: If a wrapper forwards attributes, use the relevant React HTML attribute type or derive props from the element deliberately. Remove internal props before spreading the rest onto the DOM.
  • Callback variance: Make sure a callback accepts the values the child really sends. Do not silence an incompatibility with a cast merely to satisfy a component call site.
  • Runtime data: Treat API responses, URL parameters, local storage, and submitted forms as untrusted until validated. Static types cannot change malformed runtime values.
  • Accessibility: Types can confirm that an aria-label is a string, but they cannot confirm that the label is useful or that a custom control behaves accessibly.

Keep TypeScript configuration, lint rules, and project structure aligned with the component strategy. A strict configuration and a consistent lint workflow make typing errors easier to find, while a predictable folder layout helps teams locate shared types without creating a single unmaintainable types file.

Common mistakes

Using React.FC as a default

A function declaration with an explicit props type is usually sufficient. It makes the component's inputs visible and does not imply that every component accepts children. There are valid cases for reusable component aliases, but choosing one convention should not replace understanding the component contract.

Typing everything as any

any removes the checks that make the component safer. If the shape is genuinely unknown, use unknown and narrow it. If a value has a fixed set of states, use a union. If the component is generic, preserve the relationship with a type parameter instead of erasing it.

Making all props optional

Optional props often shift errors from the call site into conditional rendering and undefined checks throughout the component. Require values that the component cannot operate without, and provide defaults at the boundary when a default is part of the design.

Overusing type assertions

An assertion such as value as User tells the compiler to trust you; it does not transform or validate the value. Use assertions at narrow, well-understood boundaries and prefer a type guard or runtime schema when the value comes from outside the application.

Spreading arbitrary props onto DOM elements

Blindly forwarding ...props can leak component-only values into the DOM and make the public API unclear. Destructure internal props first, then forward only the attributes your wrapper is designed to support.

When to revisit

Use this checklist whenever you add a component, convert a JavaScript component, introduce a shared hook, or change a public prop. Revisit it during dependency or TypeScript upgrades as well, because recommended React typings, JSX behavior, and compiler diagnostics can evolve with the toolchain.

Before merging a component API, run through this short review:

  1. Are required props genuinely required, and are optional props backed by clear behavior?
  2. Are callbacks typed at the boundary with the correct parameter and return types?
  3. Do event and ref types match the actual DOM elements?
  4. Does state represent meaningful loading, success, empty, and error cases?
  5. Are children and forwarded props intentionally constrained?
  6. Are external values validated before the component treats them as trusted domain data?
  7. Can a caller understand the component from its props type without reading its implementation?

For related project-wide practices, compare this component checklist with a maintainable TypeScript ESLint workflow, a scalable TypeScript project structure, and a strict tsconfig configuration. The goal is not to annotate every line. It is to make each React component's inputs, outputs, and failure cases clear enough that the next change is predictable.

Related Topics

#React#TypeScript#components#props#hooks#events#frontend development
T

TypeScript Website Editorial Team

Technical Editors

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.