Skip to main content

Default value for props

Short answer

In React you can set a default value for props in two main ways:

  1. Through destructuring (the modern, recommended way)
  2. Through defaultProps (deprecated, but still works for classes)

1. The modern way - through destructuring

You simply specify a default value when receiving props:

javascript
function Greeting({ name = "Guest" }) { return <h1>Hello, {name}!</h1>; }

Usage:

javascript
<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:

javascript
function Greeting({ name }) { return <h1>Hello, {name}!</h1>; } Greeting.defaultProps = { name: "Guest", };

Usage:

javascript
<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:

javascript
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:

javascript
function Greeting({ name }) { return <h1>Hello, {name || "Guest"}!</h1>; }

But this technique substitutes "Guest" even if name = "" or 0, so it does not always fit (sometimes this is undesired behavior).


4. Combined example

javascript
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:

javascript
<Profile name="Tim" /> // Name: Tim // Age: 18 // Country: Not specified

Summary

MethodExampleRecommended
Through destructuringfunction Comp({ prop = "default" }) {}Modern standard
Through defaultPropsComp.defaultProps = { prop: "default" }Classes only
Through ``

Main idea:

In modern React apps, the best place to set default values for props is right in the function's parameter destructuring:

javascript
function Button({ color = "blue", size = "medium" }) { return <button className={`${color} ${size}`}>Button</button>; }

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.