Course contentsShow
← React
Lesson 241 of 2,3967. Props FundamentalsFree lesson

Setting Default Values with Destructuring

Provide fallback values for props using default parameter syntax when destructuring in the function signature.

Setting Default Values with Destructuring

What you'll learn: How to provide fallback values for props that might not be passed to your component.

The Problem with Missing Props

When you destructure props, sometimes a parent component won't pass certain props at all. Without a default value, that prop will be undefined, which can cause bugs or unexpected behavior in your component.

The Solution: Default Parameter Syntax

You can assign default values directly in the destructuring syntax using the = operator. This is standard JavaScript default parameter syntax:

function Greeting({ name = "Guest", age = 18 }) {
  return <p>Hello {name}, you are {age} years old.</p>;
}

// Usage:
<Greeting name="Alice" age={25} />  // Hello Alice, you are 25 years old.
<Greeting name="Bob" />              // Hello Bob, you are 18 years old.
<Greeting />                         // Hello Guest, you are 18 years old.

How It Works

When you write { name = "Guest" }, you're saying: "Extract the name prop, but if it's undefined, use "Guest" instead." The default only applies when the prop is missing or explicitly undefined—not when it's null, 0, or an empty string.

Think of It Like...

Imagine ordering coffee: "I'll take a latte with oat milk, or regular milk if you're out." The default is your backup plan when the first choice isn't available.

Common Use Cases

  • Buttons with default text: { label = "Click me" }
  • Boolean flags: { isActive = false }
  • Numeric values: { count = 0 }
  • Empty arrays: { items = [] }

Key Takeaway: Use destructuring default values ({ prop = defaultValue }) to make your components more resilient when props aren't provided, preventing undefined errors and clarifying expected behavior.