Default Values vs Nullish Coalescing
What you'll learn: How to decide between destructuring defaults and using ?? or || operators to handle missing prop values.
Two Ways to Handle Missing Props
You've learned that destructuring can provide default values:
function Greeting({ name = "Guest" }) {
return <h1>Hello, {name}!</h1>;
}
But you can also handle defaults inside the component with the nullish coalescing operator (??) or logical OR (||):
function Greeting({ name }) {
const displayName = name ?? "Guest";
return <h1>Hello, {displayName}!</h1>;
}
When to Use Each Approach
Destructuring defaults apply when a prop is undefined (not passed at all). They're clean and work great for simple cases.
Nullish coalescing (??) applies when the prop is undefined or null. Use this when you want to treat both as "missing" and provide a fallback.
Logical OR (||) also catches falsy values like 0, "", or false. This can surprise you:
function Count({ count }) {
const display = count || 10; // BUG: count={0} shows 10, not 0!
return <p>{display}</p>;
}
Think of it like ordering food: destructuring defaults are like "I'll have the house special if you don't ask me," while ?? inside the component is like "Let me check what I got, and if it's nothing or null, I'll decide then."
Why Use Operators Inside?
Sometimes you need conditional logic beyond simple defaults—like computing a value based on multiple props, or combining a prop with other data. The operators give you that flexibility.
Key Takeaway: Use destructuring defaults for simple cases where undefined means "use this instead." Use ?? when you want to handle both undefined and null, and avoid || unless you truly want all falsy values to trigger the default.