defaultProps or assign default values during destructuring?

Hey campers,

Is it better use default props from prop-types?

MyComponent.defaultProps = {
  items: 0
}

or assign default values when receiving parameters?

const MyComponent = ({items = 0}) => {

}

or both? Does this make more robust or just redundant?

In a pure functional component, do it with destructuring. In class components, you’ll want to assign to the property, which you can do either with the above (defaultProps is part of react BTW, not prop-types), or use the newish class property syntax:

class MyComponent extends React.Component {
    static defaultProps = { items : 0 }
    ...
}

You may need an extra babel plugin to handle this though, namely @babel/plugin-proposal-class-properties. If you use create-react-app then this is already added for you.

1 Like

Thanks this is a really good answer.