Sub topic 3
Optional props and default values
This chapter covers how to mark props as optional, how to give them defaults, and what the compiler does with the resulting types. It assumes you know basic React (function components, props, JSX) and TypeScript fundamentals (interfaces, unions, generics). It also assumes a project already set up with "strict": true, as in the setup chapter.
What an optional prop is
A prop is optional when its name is followed by ? in the props type. The caller may leave it out, and inside the component its type includes undefined.
interface BadgeProps {
label: string;
tone?: "info" | "warning" | "error";
}
export function Badge({ label, tone }: BadgeProps) {
// Here, tone has the type "info" | "warning" | "error" | undefined
return <span className={tone ? `badge badge-${tone}` : "badge"}>{label}</span>;
}Both of these calls compile:
<Badge label="New" />
<Badge label="Careful" tone="warning" />Without a default, you must handle undefined yourself. Strict mode enforces this. If you write tone.toUpperCase() on a string | undefined prop, the compiler reports that the object is possibly undefined.
Default values with destructuring
The usual way to give an optional prop a default is a default value in the destructuring pattern.
interface CardProps {
title: string;
variant?: "plain" | "outlined";
}
export function Card({ title, variant = "plain" }: CardProps) {
// variant is "plain" | "outlined" here, with no undefined
return <section className={`card card-${variant}`}>{title}</section>;
}Two things happen here:
- At the call site,
variantstays optional, because the props type still saysvariant?. - Inside the function, TypeScript removes
undefinedfrom the type ofvariant, because the default fills it in.
This is the main reason to prefer destructuring defaults. The type that callers see and the type that the body sees are different, and the compiler tracks both.
Where the default lives
Put the default next to the destructured name, not in the interface. An interface describes shape only. It cannot hold values.
interface PagerProps {
page?: number;
pageSize?: number;
}
export function Pager({ page = 1, pageSize = 20 }: PagerProps) {
const offset = (page - 1) * pageSize; // both are plain number
return <p>Showing items from {offset}</p>;
}What counts as "missing"
A default applies only when the value is undefined. It does not apply for null, 0, "", or false.
<Pager page={undefined} /> // page becomes 1
<Pager page={0} /> // page stays 0This matters in two ways. First, passing 0 is a valid choice, and the default will not override it. Second, if a prop's type allows null, a default will not replace it, and the type inside the body still includes null.
interface AvatarProps {
src?: string | null;
}
export function Avatar({ src = "/default.png" }: AvatarProps) {
// src is string | null. null is NOT replaced by the default.
return <img src={src ?? "/default.png"} alt="" />;
}If you want both null and undefined to fall back, use ?? in the body instead of a destructuring default.
Optional versus `| undefined`
These two declarations look alike but differ.
interface A {
size?: number; // the key may be absent
}
interface B {
size: number | undefined; // the key must be present
}With A, <Comp /> compiles. With B, the caller must write size={undefined} explicitly, and omitting it is an error. For props, you almost always want ?.
There is also a compiler option, exactOptionalPropertyTypes, that separates "absent" from "present but undefined". It is off in strict. If you turn it on, size?: number rejects size={undefined}. Many libraries that pass props through do not expect this, so enable it only if you have a reason.
Choosing between optional and required
Optional props are convenient, but each one adds a branch to the component and to its tests. Use these criteria:
- Make a prop optional when a sensible default exists and most callers would use it.
- Keep a prop required when there is no safe default, such as an
idor anonSubmithandler that must do something. - Do not make a prop optional only to silence a compile error at one call site. That moves the bug to runtime.
A related decision is whether to make optional callbacks default to a no-op:
interface DialogProps {
title: string;
onClose?: () => void;
}
export function Dialog({ title, onClose }: DialogProps) {
return (
<div role="dialog" aria-label={title}>
<button onClick={() => onClose?.()}>Close</button>
</div>
);
}Optional chaining (onClose?.()) is the usual choice for callbacks. A default such as onClose = () => {} also works, but it creates a new function on every render, which can defeat memoization in child components. If you want a stable default, define it once outside the component.
const noop = () => {};
export function Dialog2({ title, onClose = noop }: DialogProps) {
return (
<div role="dialog" aria-label={title}>
<button onClick={onClose}>Close</button>
</div>
);
}Defaults for objects and arrays
A default object or array written inline in the parameter list is created again on every render.
interface ListProps {
items?: string[];
}
// Creates a new empty array each render when items is omitted
export function Bad({ items = [] }: ListProps) {
return <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
}This is harmless for simple rendering. It becomes a problem when items is a dependency of useEffect, useMemo, or useCallback, because a new array each render means the dependency always looks changed. Hoist the default to a module constant.
const EMPTY: readonly string[] = [];
export function Better({ items = EMPTY }: { items?: readonly string[] }) {
return <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
}Common errors
| Symptom | Cause | Fix | Column |
|---|---|---|---|
| "Object is possibly undefined" on a prop | Optional prop used without a default or check | Add a destructuring default, or narrow with `if` or `?.` | |
| Default is ignored when caller passes `null` | Defaults apply only to `undefined` | Use `??` in the body, or remove `null` from the type | |
| Effect re-runs every render | Inline `[]` or `{}` default used as a dependency | Hoist the default to a module constant | |
| Caller must pass `prop={undefined}` | Prop typed `x: T \ | undefined` instead of `x?: T` | Change to `x?: T` |
| Default value type is wider than the prop type | Default does not match the declared type | Fix the default, since it is checked against the prop type |
The last row is worth seeing. The compiler checks defaults against the declared type:
interface ToneProps {
tone?: "info" | "error";
}
// Error: Type '"warning"' is not assignable to type '"info" | "error" | undefined'
export function Tone({ tone = "warning" }: ToneProps) {
return <span>{tone}</span>;
}Older approaches you may still see
Older code sets defaults with Component.defaultProps = { ... }. React has removed support for defaultProps on function components in React 19, and it is deprecated in earlier versions. Use destructuring defaults in new code. When you read old code, convert defaultProps to destructuring defaults and keep the ? marker on the prop.
Summary of rules
- Mark a prop optional with
?in the props type. - Set its default in the destructuring pattern, not in the interface.
- Remember that defaults apply only to
undefined. - Hoist default objects, arrays, and functions to module constants when they feed hooks or memoized children.
- Handle optional callbacks with
?.(), or give them a stable no-op.
Exercise
A component declares interface BoxProps { padding?: number } and destructures { padding = 8 }. A caller renders <Box padding={0} />. What padding does the component see, and what is the type of padding inside the body?
Show answer
The component sees 0, because destructuring defaults apply only when the value is undefined, and 0 is a defined value. Inside the body the type is number, since the default removes undefined from the type. The caller-facing type is still number | undefined, so padding stays optional at call sites.
Exercise
This component re-runs its effect on every render. Explain why and show the fix. function Results({ filters = {} }: { filters?: Record<string, string> }) { useEffect(() => { fetchResults(filters); }, [filters]); return null; }
Show answer
When filters is omitted, the default {} is a new object on each render. React compares dependencies by reference, so the effect sees a changed value every time. Hoist the default: const NO_FILTERS: Record<string, string> = {}; and use filters = NO_FILTERS. The reference is then the same across renders.