Sub topic 3
Destructuring props and setting default values
This chapter assumes you know basic JavaScript destructuring, arrow functions, and how to render a function component in a Vite React project. You should also know how to pass props as JSX attributes. The chapter covers how to read props cleanly, how to make them optional, and where defaults behave in ways people don't expect.
From the props object to destructured parameters
React calls your function component with one argument, an object that holds every prop the parent passed. You can read values from it directly:
function Avatar(props) {
const size = props.size === undefined ? 48 : props.size;
return (
<div style={{ width: size, height: size }}>
{props.name[0]}
</div>
);
}Writing props. before every value gets noisy as a component grows. Destructuring the parameter lists the inputs once, at the top, and doubles as documentation of what the component accepts:
function Avatar({ name, size = 48, rounded = true }) {
const style = {
width: size,
height: size,
borderRadius: rounded ? '50%' : 0,
background: '#ddd',
display: 'grid',
placeItems: 'center',
};
return <div style={style}>{name[0]}</div>;
}
export default function App() {
return (
<div>
<Avatar name="Grace" />
<Avatar name="Linus" size={64} rounded={false} />
</div>
);
}Avatar has one required prop, name, and two optional props, size and rounded. Anyone reading the signature can see that.
You can also destructure inside the body. The result is the same:
function Avatar(props) {
const { name, size = 48, rounded = true } = props;
return <div>{name[0]}</div>;
}Use the body form when you need the whole props object elsewhere, for example to pass it to a helper. Otherwise prefer the parameter form.
How default values work
A default in a destructuring pattern is ordinary JavaScript. The default is used only when the value is exactly undefined. A prop is undefined in two cases:
- The parent did not pass it.
- The parent passed it explicitly as
undefined.
The diagram shows how a value is resolved.
Values that skip the default
Because only undefined triggers the default, these values pass through unchanged:
| Parent passes | Child receives | Default applied? |
|---|---|---|
| nothing | `undefined` | Yes |
| `size={undefined}` | `undefined` | Yes |
| `size={null}` | `null` | No |
| `size={0}` | `0` | No |
| `label=""` | `""` | No |
| `rounded={false}` | `false` | No |
This is usually what you want, since 0 and false are legitimate values. The common trap is null. Data from an API often arrives as null, and a default will not replace it:
function UserName({ name = 'Anonymous' }) {
return <p>{name}</p>;
}
// Renders "Anonymous"
<UserName />
// Renders an empty paragraph, because null is not undefined
<UserName name={null} />If you want null to fall back too, handle it explicitly inside the component:
function UserName({ name }) {
return <p>{name ?? 'Anonymous'}</p>;
}The nullish coalescing operator ?? replaces both null and undefined, but keeps 0, "", and false. Avoid || for this job. It would also replace 0 and false, which makes size={0} impossible to pass.
Boolean props and the shorthand
In JSX, an attribute with no value is the same as {true}:
function Badge({ label, highlighted = false }) {
return (
<span style={{ fontWeight: highlighted ? 'bold' : 'normal' }}>
{label}
</span>
);
}
export default function App() {
return (
<p>
<Badge label="New" highlighted />
<Badge label="Old" />
<Badge label="Sale" highlighted={false} />
</p>
);
}Choose boolean defaults so that the common case needs no attribute. A prop named highlighted with default false is easy to use as <Badge highlighted />. A prop with default true, such as rounded = true in Avatar, forces callers to write rounded={false} to turn it off. That works, but a name like square with default false often reads better.
Renaming and nested destructuring
You can rename a prop while destructuring. The syntax is propName: localName. A default follows the local name:
function Price({ value: amount = 0, currency: code = 'USD' }) {
return (
<span>
{amount.toFixed(2)} {code}
</span>
);
}
<Price value={19.5} />Renaming helps when a prop name clashes with a variable in scope, or when the public name suits the caller better than the internal one. In the parameter above, value and currency no longer exist as variables inside the function. Only amount and code do.
Nested destructuring reaches into object props:
function UserCard({ user: { name, email = 'no email on file' } }) {
return (
<div>
<h3>{name}</h3>
<p>{email}</p>
</div>
);
}
<UserCard user={{ name: 'Ada' }} />This has a sharp edge. If the parent omits user, JavaScript tries to destructure undefined and throws TypeError: Cannot destructure property 'name' of 'undefined'. The inner default for email cannot help, because it belongs to the nested pattern. Give the object itself a default as well:
function UserCard({ user: { name = 'Guest', email = 'no email on file' } = {} }) {
return (
<div>
<h3>{name}</h3>
<p>{email}</p>
</div>
);
}The = {} after the nested pattern applies when user is undefined. Deeply nested parameter patterns get hard to read quickly. When you pass more than one level down, it is usually clearer to take user as a single prop and read its fields in the body.
Object and array defaults
A default expression runs every time it is needed, which means every render in which the prop is missing. A default of {} or [] therefore creates a new object each time:
function TagList({ tags = [] }) {
return (
<ul>
{tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul>
);
}For rendering this is harmless. It matters only when you pass that value on to something that compares references, such as a memoized child or a dependency array. That topic belongs to the chapter on re-rendering and memo. If you hit it, move the default to a constant outside the component:
const NO_TAGS = [];
function TagList({ tags = NO_TAGS }) {
return (
<ul>
{tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul>
);
}The same constant is used on every render, so its reference never changes.
Defaults computed from other props
Later parameters in a destructuring pattern can use earlier ones, because defaults are evaluated left to right:
function Square({ size = 40, border = size / 10 }) {
return (
<div style={{ width: size, height: size, border: `${border}px solid black` }} />
);
}border is only valid after size appears in the pattern. Swapping their order would throw a ReferenceError. Use this sparingly. If the relationship is more than a simple expression, compute the value in the body instead.
Collecting the rest of the props
You can pull out the props you care about and keep the rest in one object with the rest pattern:
function TextInput({ label, ...rest }) {
return (
<label>
{label}
<input {...rest} />
</label>
);
}rest holds every prop except label. A later chapter covers forwarding props with the spread syntax in detail. Here, note only that defaults still work alongside rest: { label = 'Name', ...rest } is valid.
Do not use defaultProps in new code
Older class and function components set defaults with a defaultProps property:
function Avatar({ name, size }) {
return <div style={{ width: size, height: size }}>{name[0]}</div>;
}
Avatar.defaultProps = { size: 48 };React 18.3 logs a deprecation warning for this on function components, and React 19 removes support for it. Default parameter values are the replacement. They keep the default next to the code that uses it and work the same way for undefined.
Common errors
- Reading a missing required prop.
name[0]throws ifnameisundefined. Decide whether a prop is required. If it is, a TypeScript type (covered in a later chapter) catches the omission at build time. - Expecting a default for
null. Use??in the body. - Using
||for defaults. It overrides valid0,"", andfalse. - Destructuring a nested object with no default. Add
= {}or read it in the body. - Writing
prop = valuein JSX. Defaults belong in the function signature. In JSX, attributes useprop={value}orprop="text". - Mutating a destructured object. Destructuring copies references, not objects. Changing
user.namestill changes the parent's data. Props are read-only, as a later chapter explains.
Exercise
A component is defined as function Counter({ start = 10 }) { return <p>{start}</p>; }. What does it render for <Counter />, <Counter start={0} />, and <Counter start={null} />?
Show answer
<Counter /> renders 10, because the prop is undefined and the default applies. <Counter start={0} /> renders 0, because 0 is a passed value and does not trigger the default. <Counter start={null} /> renders an empty paragraph, because null is not undefined, so the default is skipped and React renders nothing for null. To get 10 in the last case, read the value with start ?? 10 in the body.
Exercise
Rewrite function Alert(props) { const type = props.type || 'info'; const dismissible = props.dismissible || true; return <div className={type}>{props.message}</div>; } using destructured parameters and defaults. Which line has a bug, and what is it?
Show answer
function Alert({ message, type = 'info', dismissible = false }) { return <div className={type}>{message}</div>; }. The dismissible line has the bug: props.dismissible || true always evaluates to true, even when the parent passes false, because false || true is true. A default parameter only replaces undefined, so dismissible={false} stays false. The default of false here is a choice, so that <Alert dismissible /> is the way to turn the feature on.