What are explicit defaultProps?

Browsing around the internet, I stumbled on Airbnb’s javascript Github repo where they keep a list of best practices on JavaScript. Not only on JS but on CSS, React, CSS-in-JavaScript, and lots more. So I decided to share with you an important rule on writing React here.

Most of them are based on making our React code clearer and cleaner, few of them make our React app run faster.

You can look up the full style guide here, we will look into defining explicit defaultProps today.

Define explicit defaultProps

defaultProps is a static property set on components that hold the default values of props that the component receives. The default values kick in when the specified props are missing during the component render.

The React style guide states that all non-required props should be defined in defaultProps.

Yes, setting defaultProps tells your readers the props they can omit and don’t have to assume too much.

Let’s have a look at an example:

    // bad

    function Component({propOne, propTwo}) {
        // ...
    }

    Component.propTypes = {
        propOne: PropTypes.number.isRequired,
        propTwo: PropTypes.string
    }

The Component requires two props:

  1. propOne
  2. propTwo

It has a propTypes static property that defines the data types of the props, and if they are required, i.e. it must be passed to the Component.

propOne is a number type and is required to be present. propTwo is a string type and is optional.

Here we set an empty string as the default value of propTwo. Now, propTwo default values should be set, so your code is predictable.

    // good

    function Component({propOne, propTwo}) {
        // ...
    }

    Component.propTypes = {
        propOne: PropTypes.number.isRequired,
        propTwo: PropTypes.string
    }

    Component.defaultProps = {
        propTwo: ""
    }