Default value for props
Short answer
In React you can set a default value for props in two main ways:
- Through destructuring (the modern, recommended way)
- Through
defaultProps(deprecated, but still works for classes)
1. The modern way - through destructuring
You simply specify a default value when receiving props:
function Greeting({ name = "Guest" }) {
return <h1>Hello, {name}!</h1>;
}Usage:
<Greeting name="Tim" /> // Hello, Tim!
<Greeting /> // Hello, Guest!React substitutes "Guest" if name was not passed (or is undefined).
This only works when the value is missing - if name={null}, the default value is not substituted.
2. The old way - through defaultProps
Previously used for classes and for functional components before hooks appeared:
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
Greeting.defaultProps = {
name: "Guest",
};Usage:
<Greeting /> // Hello, Guest!
<Greeting name="Maria" /> // Hello, Maria!Starting with React 17, defaultProps is officially not recommended
for functional components - destructuring is preferred instead.
But it still works for classes:
class Greeting extends React.Component {
static defaultProps = {
name: "Guest",
};
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}3. Through a logical "OR" (an alternative technique)
Sometimes you can set the value right in JSX:
function Greeting({ name }) {
return <h1>Hello, {name || "Guest"}!</h1>;
}But this technique substitutes
"Guest"even ifname = ""or0, so it does not always fit (sometimes this is undesired behavior).
4. Combined example
function Profile({ name = "No name", age = 18, country = "Not specified" }) {
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Country: {country}</p>
</div>
);
}Usage:
<Profile name="Tim" />
// Name: Tim
// Age: 18
// Country: Not specifiedSummary
| Method | Example | Recommended |
|---|---|---|
| Through destructuring | function Comp({ prop = "default" }) {} | Modern standard |
Through defaultProps | Comp.defaultProps = { prop: "default" } | Classes only |
| Through ` | ` |
Main idea:
In modern React apps, the best place to set default values for
propsis right in the function's parameter destructuring:javascriptfunction Button({ color = "blue", size = "medium" }) { return <button className={`${color} ${size}`}>Button</button>; }
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.