ReactEasy

What are default props?

Default props are fallback values used when a parent does not pass a prop. In function components, set them with JavaScript default parameters in destructuring: function Button({ size = "md" }). The Component.defaultProps static property was removed for function components in React 19 and only remains for class components.

Function components (current)

  • function Avatar({ size = 40, shape = "circle", alt = "" }).
  • Defaults apply when the prop is undefined, not when it is null.
  • In TypeScript, mark the prop optional (size?: number) and the default narrows the type inside the component.

Class components

static defaultProps = { size: 40 } still works for classes.

History

defaultProps on function components was deprecated in React 18.3 and removed in React 19: values set that way are ignored. Codemods can convert them to default parameters.

Pitfalls

  • Default objects or arrays (items = []) create a new reference every render. That is fine for rendering, but if the value is used as an effect dependency or passed to a memoized child, define the default as a module-level constant: const EMPTY: Item[] = [].
  • Defaults are for optional configuration. Required data should be a required prop, so TypeScript catches omissions.

Code example

tsx
1type AvatarProps = {
2 src?: string;
3 name: string;
4 size?: number;
5 shape?: "circle" | "square";
6 tags?: string[];
7};
8
9const NO_TAGS: string[] = []; // stable default reference
10
11export function Avatar({ src, name, size = 40, shape = "circle", tags = NO_TAGS }: AvatarProps) {
12 return (
13 <figure>
14 {src ? (
15 <img src={src} alt={name} width={size} height={size} style={{ borderRadius: shape === "circle" ? "50%" : 4 }} />
16 ) : (
17 <span style={{ width: size, height: size }} className="avatar-fallback">{name[0]}</span>
18 )}
19 {tags.length > 0 && <figcaption>{tags.join(", ")}</figcaption>}
20 </figure>
21 );
22}
23
24// Removed in React 19 for function components (silently ignored):
25// Avatar.defaultProps = { size: 40 };

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app