How to Use default props in React?

I’ve seen many developers struggle with undefined values in their components.

Handling missing data gracefully is what separates a professional application from one that crashes on the first minor error.

In this tutorial, I will show you how to master React component default props to ensure your UI remains stable and predictable.

What Are Default Props in React?

When you build a reusable component, you often pass data to it via props. But what happens if a specific piece of data isn’t provided?

Without a fallback, your component might try to render undefined or null, often leading to the dreaded “cannot read property of undefined” error.

Default props allow you to define “plan B” values for your components, ensuring they have data to work with even when the parent component forgets to send it.

Method 1: Use Default Parameters (Functional Components)

Modern React development has moved heavily toward functional components. In my experience, the cleanest way to handle defaults is through ES6 destructuring.

I prefer this method because it uses standard JavaScript syntax and keeps the logic right where the props are declared.

Let’s look at a practical example involving a US Sales Tax Calculator.

import React from 'react';

// Functional component using ES6 default parameters
const SalesTaxSummary = ({ 
    stateName = "Delaware", 
    taxRate = 0.0, 
    subtotal = 100 
}) => {
    const totalTax = (subtotal * (taxRate / 100)).toFixed(2);
    const finalAmount = (parseFloat(subtotal) + parseFloat(totalTax)).toFixed(2);

    return (
        <div style={{ padding: '20px', border: '1px solid #ddd', borderRadius: '8px' }}>
            <h2>Tax Summary for {stateName}</h2>
            <p>Subtotal: ${subtotal}</p>
            <p>State Tax Rate: {taxRate}%</p>
            <hr />
            <h3>Total Amount: ${finalAmount}</h3>
            {taxRate === 0 && <p><em>Note: This state has no sales tax.</em></p>}
        </div>
    );
};

// Usage Example
const App = () => {
    return (
        <div>
            <h1>Checkout Page</h1>
            {/* Here we miss passing props, so it uses the defaults */}
            <SalesTaxSummary />
            
            {/* Here we provide specific props for California */}
            <SalesTaxSummary stateName="California" taxRate={7.25} subtotal={250} />
        </div>
    );
};

export default App;

You can refer to the screenshot below to see the output.

Use default props in React

In the example above, if the stateName is missing, the component defaults to Delaware, which is famous for having 0% sales tax.

This approach is highly readable and is currently the industry standard for React versions 16.8 and above.

Method 2: The defaultProps Property (Functional Components)

While ES6 defaults are popular, React still supports the defaultProps property.

I find this useful when I want to keep the function signature clean or when working with older codebases.

Let’s use an example of a US Presidential Election Tracker card.

import React from 'react';

const ElectionCard = (props) => {
    return (
        <div className="election-card" style={{ margin: '10px', padding: '15px', background: '#f4f4f4' }}>
            <h3>Candidate: {props.candidateName}</h3>
            <p>Party: {props.party}</p>
            <p>Current Electoral Votes: {props.votes}</p>
        </div>
    );
};

// Defining default props outside the function
ElectionCard.defaultProps = {
    candidateName: "TBD",
    party: "Independent",
    votes: 0
};

const ElectionDashboard = () => {
    return (
        <div>
            <h2>2024 Election Monitor</h2>
            {/* Uses all defaults */}
            <ElectionCard />
            
            {/* Overrides some defaults */}
            <ElectionCard candidateName="John Doe" party="Democrat" votes={20} />
            <ElectionCard candidateName="Jane Smith" party="Republican" votes={15} />
        </div>
    );
};

export default ElectionDashboard;

You can refer to the screenshot below to see the output.

default props in React

Using defaultProps is very explicit. It tells other developers exactly what the fallback data looks like at a glance.

However, note that React recently deprecated defaultProps for functional components in newer versions, encouraging the use of ES6 parameters instead.

Method 3: Default Props in Class Components

Even though Hooks are the trend, many large-scale enterprise applications in the US still rely on Class Components.

In my years of consulting, I’ve seen massive fintech dashboards built entirely on classes.

Here is how you handle defaults in a class-based 401k Retirement Planner.

import React, { Component } from 'react';

class RetirementPlanner extends Component {
    // Static property for default props
    static defaultProps = {
        employerMatch: 3, // 3% default match
        currentAge: 30,
        retirementAge: 65,
        annualContribution: 6000
    };

    render() {
        const { employerMatch, currentAge, retirementAge, annualContribution } = this.props;
        const yearsToInvest = retirementAge - currentAge;

        return (
            <div style={{ border: '2px solid blue', padding: '20px' }}>
                <h2>Retirement Goal: Age {retirementAge}</h2>
                <p>Starting at age {currentAge}, you have {yearsToInvest} years left to save.</p>
                <p>With a {employerMatch}% employer match, your annual savings strategy is solid.</p>
                <p>Expected Annual Contribution: ${annualContribution}</p>
            </div>
        );
    }
}

const FinancialApp = () => {
    return (
        <div>
            <h1>US Wealth Management Tool</h1>
            {/* Uses default values for age and match */}
            <RetirementPlanner annualContribution={10000} />
        </div>
    );
};

export default FinancialApp;

You can refer to the screenshot below to see the output.

How to Use default props in React

In class components, using the static defaultProps syntax is the most professional way to organize your code.

It keeps the configuration separate from the rendering logic, which is vital for maintaining large files.

Handle Nested Objects as Default Props

One mistake I often see is trying to set default props for individual properties inside an object.

If you pass an object prop, the default only kicks in if the entire object is missing, not just a single key.

Let’s look at a US Shipping Address component to see the right way to handle this.

import React from 'react';

const ShippingLabel = ({ address }) => {
    // Handling nested defaults manually or via destructuring
    const { 
        name = "Valued Customer", 
        street = "1600 Pennsylvania Avenue NW", 
        city = "Washington", 
        state = "DC", 
        zip = "20500" 
    } = address || {};

    return (
        <div style={{ padding: '10px', border: '1px black dashed', width: '300px' }}>
            <strong>Ship To:</strong><br />
            {name}<br />
            {street}<br />
            {city}, {state} {zip}<br />
            United States
        </div>
    );
};

const StoreCheckout = () => {
    const partialAddress = { name: "Alice Johnson" };

    return (
        <div>
            <h2>Standard Shipping</h2>
            {/* address is missing, so it uses the fallbacks via (address || {}) */}
            <ShippingLabel />

            <h2>Partial Address Provided</h2>
            {/* name is provided, but other keys will be undefined unless handled inside */}
            <ShippingLabel address={partialAddress} />
        </div>
    );
};

export default StoreCheckout;

When dealing with objects, I always recommend the address || {} pattern followed by destructuring with defaults.

This prevents your app from crashing if the address prop is null.

Why Should You Use Default Props?

Throughout my career, I’ve found three main reasons why this practice is non-negotiable:

  1. Preventing UI Breakage: It ensures your layout doesn’t shift or break because a string was expected, but an undefined value was received.
  2. Code Documentation: It serves as a form of documentation for other developers, showing what data types are expected.
  3. Easier Testing: When you write unit tests, you don’t have to provide every single prop for every test case.

Whether you are building a small personal project or a major application for a US-based corporation, default props are your first line of defense.

I hope you found this tutorial helpful! Using these methods will make your React components much more resilient.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.