Sub topic 3
Destructuring props and setting default values
This chapter assumes you know JavaScript object destructuring and default parameter values. It also assumes you can write a function component and pass it props, as covered in the previous chapter.
From `props.x` to destructured parameters
A component receives one argument, the props object. You can read fields from it directly:
function Avatar(props) {
return <div>{props.name[0]}</div>;
}Repeating props. gets noisy as the list grows. It also hides which props the component actually uses. Destructuring the argument in the parameter list fixes both problems:
function Avatar({ name, size = 48, rounded = true }) {
const style = { width: size, height: size, borderRadius: rounded ? '50%' : 0 };
return <div style={style}>{name[0]}</div>;
}
export default function App() {
return (
<>
<Avatar name="Grace" />
<Avatar name="Linus" size={64} rounded={false} />
</>
);
}The parameter list now documents the component's inputs. name has no default, so callers must supply it. size and rounded have defaults, so callers may leave them out.
How defaults work
A default value applies when the prop is undefined. That happens in two cases: the parent omitted the prop, or the parent passed undefined explicitly.
The condition is "is undefined", not "is falsy". These values do not trigger a default:
| Value passed | Default used? |
|---|---|
| omitted | yes |
| `undefined` | yes |
| `null` | no |
| `0` | no |
| `""` | no |
| `false` | no |
So <Avatar name="Ada" size={null} /> sets size to null, and the avatar gets no usable width. If your data can contain null, handle it yourself, for example with size ?? 48 inside the component.
Renaming, nesting, and rest
Destructuring has the same options as in plain JavaScript:
function UserBadge({ user: { name, role = 'guest' }, size: badgeSize = 24 }) {
return (
<span style={{ fontSize: badgeSize }}>
{name} ({role})
</span>
);
}
export default function App() {
return <UserBadge user={{ name: 'Ada' }} />;
}Here size: badgeSize renames the prop for local use, and user: { name, role } reaches inside an object prop. Nested destructuring throws a TypeError if user is missing, because there is nothing to destructure. Use it only for props the caller must provide. For optional objects, give the whole prop a default, such as user = {}.
Defaults for objects and arrays
Parameter defaults are evaluated on each render. A default of [] or {} is therefore a new object every time the component renders without that prop:
function List({ items = [] }) {
return (
<ul>
{items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}This is fine for rendering. It becomes a problem if you pass items to a memoized child or list it in a hook dependency array, because the reference changes each render. In those cases, define the default once outside the component:
const EMPTY_ITEMS = [];
function List({ items = EMPTY_ITEMS }) {
return <ul>{items.map((item) => <li key={item}>{item}</li>)}</ul>;
}Common mistakes
- Destructuring in the parameter list without braces:
function Avatar(name, size)readsnameas the whole props object. Wrap the names in{ }. - Expecting a default for a required prop. Defaults only help when omitting the prop is valid.
- Reassigning a destructured value and expecting the parent to change. Destructured names are local copies of the values. The next chapter covers why props are read-only.
Exercise
A component is declared as function Badge({ count = 10 }). What value does count have for <Badge count={null} />, and why?
Show answer
It is null. Defaults apply only when the value is undefined, and null is a defined value. To fall back to 10 for null as well, write const safeCount = count ?? 10 inside the component.
Exercise
Why might you move a default of [] out of the parameter list and into a module-level constant?
Show answer
A default in the parameter list creates a new array on every render. If that array goes to a memoized child or a hook dependency array, the changing reference defeats the optimization. A module-level constant keeps the same reference across renders.