Skip to content

React and TypeScript at Scale ​

Type props, state, refs and context so that the wrong state cannot be written down, and a hundred components stay refactorable.

In this chapter: props as a contract · state that cannot be invalid · generic components · refs and context · typing the server boundary

💡 The Core Idea ​

A React component is a function, so typing one is typing a function: name the props, name the return. That much is mechanical. What separates a codebase that scales from one that merely compiles is what you choose to model.

The move that pays most is to make invalid states unrepresentable. { loading, data, error } as three independent fields describes eight combinations. Four are nonsense, such as loading with an error and data, and every consumer has to defend against all eight. A discriminated union describes four, and the compiler narrows to exactly one. That single change removes more defensive branches from a large React codebase than any other typing decision.

⚠️ Moving target: React 19 made ref an ordinary prop, so forwardRef is redundant and heading for deprecation. Hook typings also shift between @types/react majors. The lasting principle: props are a typed contract and hooks are generic functions. The helper names move around it.

How It Works ​

Props are a contract between two files ​

tsx
interface UserCardProps {
  name: string;
  role: "admin" | "editor" | "viewer";
  avatarUrl?: string;
  onEdit: (id: number) => void;
}

function UserCard({ name, avatarUrl, onEdit }: UserCardProps) {
  return (
    <div>
      {avatarUrl !== undefined && <img src={avatarUrl} alt={name} />}
      <button onClick={() => onEdit(1)}>Edit</button>
    </div>
  );
}

Prefer a plain function with an explicit props interface over React.FC. It used to imply children, it blocks generic components, and it adds nothing now that it does not.

NeedType
Anything renderable as a childReact.ReactNode
A render prop or a slot(item: T) => React.ReactNode
All the native attributes tooextends React.ButtonHTMLAttributes<HTMLButtonElement>
A ref to the underlying elementref?: React.Ref<HTMLButtonElement> — a normal prop in React 19

Extending native props is what makes a design-system component usable:

tsx
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: "primary" | "danger";
  loading?: boolean;
  ref?: React.Ref<HTMLButtonElement>; // React 19 — no forwardRef wrapper
}

function Button({ variant = "primary", loading, children, ...rest }: ButtonProps) {
  return (
    <button className={`btn-${variant}`} disabled={loading === true || rest.disabled} {...rest}>
      {loading === true ? "Loading…" : children}
    </button>
  );
}

Every native attribute, such as type, aria-label or onFocus, keeps working and stays checked.

For events, use React.MouseEvent<HTMLButtonElement>, React.ChangeEvent<HTMLInputElement> and React.FormEvent<HTMLFormElement>. Read currentTarget, which is typed as the element the handler is attached to. target is whatever was actually clicked, so its type is loose.

State that cannot be invalid ​

tsx
// ❌ Eight combinations, four of them meaningless
interface BadState { loading: boolean; data: User | null; error: string | null }

// ✅ Four, and the compiler narrows to one
type RequestState =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: User }
  | { status: "error"; message: string };

With the union, state.data does not exist until status === "success". So the "render the data while loading" bug becomes a compile error, not a code review comment.

useReducer is where the same idea pays twice, because the action union is checked at every dispatch:

tsx
type CartAction =
  | { type: "add"; item: CartItem }
  | { type: "remove"; itemId: 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.item.price };
    case "remove":
      return { ...state, items: state.items.filter((i) => i.id !== action.itemId) };
    case "clear":
      return { items: [], total: 0 };
    default: {
      const exhaustive: never = action; // a new action type breaks the build here
      return exhaustive;
    }
  }
}

dispatch({ type: "add" }) without an item will not compile, and neither will a typo in type.

Two useState annotations are worth knowing. Annotate when null hides the real type. Annotate an empty array too, because useState([]) widens to never[] and nothing can ever be added to it.

tsx
const [count, setCount] = useState(0);                 // inferred: number
const [user, setUser] = useState<User | null>(null);   // null alone tells the compiler nothing
const [users, setUsers] = useState<User[]>([]);        // [] alone infers never[]
const timer = useRef<ReturnType<typeof setInterval> | null>(null);

Generic components ​

A generic component keeps the caller's exact type all the way through. That is what lets one List serve every entity in the application.

tsx
interface ListProps<T> {
  items: readonly T[];
  getKey: (item: T) => string;
  renderItem: (item: T) => React.ReactNode;
}

function List<T>({ items, getKey, renderItem }: ListProps<T>) {
  return <ul>{items.map((item) => <li key={getKey(item)}>{renderItem(item)}</li>)}</ul>;
}

// `item` is User inside both callbacks — no annotation at the call site
<List items={users} getKey={(u) => u.id} renderItem={(u) => u.name} />;

The same reasoning applies to custom hooks. useFetch<User>(url) returning { data: User | null; status: RequestState["status"] } gives the caller a typed value with no cast. Note what it does not do. The type argument asserts the response shape. It does not check it. Validate at the boundary — see TypeScript Type Guards.

Context without | undefined in every consumer ​

tsx
// `undefined` as the default is deliberate: it makes "used outside the
// provider" a detectable state rather than a silently wrong default
const AuthContext = createContext<AuthContextValue | undefined>(undefined);

function useAuth(): AuthContextValue {
  const ctx = useContext(AuthContext);
  if (ctx === undefined) throw new Error("useAuth must be used within <AuthProvider>");
  return ctx; // narrowed, so consumers never see undefined
}

The throwing accessor hook is what removes | undefined from every consumer. Without it, each component handles a case that should be impossible. In React 19 the provider is the context itself: <AuthContext value={auth}>, with .Provider now optional.

Typing across the server boundary ​

Two React 19 concepts have typing rules that only exist because of the server/client split.

Props crossing into a Client Component must be serialisable. TypeScript will happily accept onSave: () => void on a Client Component rendered from a Server Component, but it fails at runtime. The type system does not model the boundary, so the discipline is yours. Props that cross it are data, plus Server Functions.

Actions have a fixed shape, and typing the state is what makes the error path safe:

tsx
interface FormState {
  error: string | null;
}

const [state, submitAction, isPending] = useActionState<FormState, FormData>(
  async (_prev: FormState, formData: FormData): Promise<FormState> => {
    const parsed = ProfileSchema.safeParse(Object.fromEntries(formData));
    if (!parsed.success) return { error: "Check the highlighted fields" };
    await updateProfile(parsed.data); // parsed.data is typed and validated
    return { error: null };
  },
  { error: null },
);

FormData values are string | File | null, never the shape you want. A runtime schema parse turns them into a typed object. The same parse also stops a hand-crafted request from reaching your database.

When to Use It ​

ScenarioReach forWhy
A component wrapping a native elementextends …HTMLAttributes<T>Every native prop stays typed and forwardable
Async data with loading and error statesA discriminated union on statusThe impossible combinations stop existing
Several values that change togetheruseReducer with an action unionInvalid dispatches fail to compile
One component reused across entity typesA generic component or hookThe caller's type survives to the callbacks
Shared state read by many componentsContext plus a throwing accessor hookConsumers never handle the undefined case
Data arriving from a network or a formA runtime schema, then the typeTypes erase; the boundary needs a real check

Common Mistakes ​

❌ useState([]) with no type argument. It infers never[], so nothing can ever be added.

❌ React.FC<Props>. It used to add an implicit children, it blocks generic components, and it buys nothing a plain annotated function does not.

❌ createContext({} as AuthContextValue). The cast makes a missing provider undetectable, so the failure surfaces as undefined is not a function deep inside a child. Default to undefined and throw in the accessor.

❌ Boolean flags where a union belongs:

tsx
// ❌ isLoading && isError && data — what does that mean?
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [data, setData] = useState<User | null>(null);

Every consumer now writes its own guess about which combinations are real. One union replaces all of them.

❌ Still writing forwardRef in React 19. ref is a normal prop now. The wrapper adds a layer and will be deprecated. In a codebase still on React 18, forwardRef<HTMLInputElement, Props> remains correct, so check the version before changing anything.

❌ Treating a type argument as validation. await res.json() as User is an assertion, not a check. The compiler stops asking questions and the runtime finds out later, in a component that cannot explain itself.

🔑 Key Takeaways ​

  • A props interface is a contract between files. Annotate it explicitly and skip React.FC.
  • A discriminated union on status removes the impossible combinations that boolean flags create.
  • An action union plus a never default turns every invalid dispatch into a compile error.
  • Default a context to undefined and throw in the accessor hook, so consumers never handle it.
  • Types erase at runtime. Validate data crossing a network or form boundary with a real schema parse.

Interview Questions ​

Q: Why model async state as a union rather than loading, data and error fields?

Three independent fields describe eight combinations, and only four are meaningful. So every consumer writes defensive branches for states that cannot happen, and one day one of them gets it wrong. A union on status narrows to a single variant, so data is only reachable once the request succeeded. The invalid states stop being handled because they can no longer be expressed.

Q: What does typing useReducer actions as a discriminated union buy you?

Every dispatch is checked against the union, so a missing field or a mistyped action name fails at the call site. Inside the reducer, switching on type narrows the action, so only that variant's fields are accessible. Assigning the action to never in the default branch turns a newly added action into a build failure, not a silent no-op.

Q: Why default a context to undefined rather than casting an empty object?

The cast makes a missing provider look the same as a real one. The failure then surfaces as a confusing runtime error inside a child component. undefined is a state the accessor hook can detect and turn into a clear message. The narrowing also means every consumer receives a non-optional value.

Q: Does TypeScript stop you passing a function to a Client Component from a Server Component?

No, and that is the trap. The type system has no model of the server/client boundary. So the code compiles, then fails at render when React tries to serialise the prop. The author has to hold the rule: what crosses that boundary is data, or a Server Function, and nothing else.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.