React functional component default props vs default parameters

In a React functional component, which is the better approach to set default props, using Component.defaultProps, or using the default parameters on the function definition, examples:

Default props:

const Component = ({ prop1, prop2 }) => (
  <div></div>
)

Component.defaultProps = {
  prop1: false,
  prop2: 'My Prop',
}

Default parameters:

const Component = ({ prop1 = false, prop2 = 'My Prop' }) => (
  <div></div>
)    

defaultProps on functional components will eventually be deprecated (as per Dan Abramov, one of the core team), so for future-proofing it's worth using default parameters.


In general (ES6), the second way is better.

In specific (in React context), the first is better since it is a main phase in the component lifecycle, namely, the initialization phase.

Remember, ReactJS was invented before ES6.


First one can cause some hard-to-debug performance problems, especially if you are using redux.

If you are using objects or lists or functions, those will be new objects on every render. This can be bad if you have complex components that check the component idenitity to see if rerendering should be done.

const Component = ({ prop1 = {my:'prop'}, prop2 = ['My Prop'], prop3 = ()=>{} }) => {(
  <div>Hello</div>
)}

Now that works fine, but if you have more complex component and state, such as react-redux connected components with database connection and/or react useffect hooks, and component state, this can cause a lot of rerending.

It is generally better practice to have default prop objects created separately, eg.

const Component = ({prop1, prop2, prop3 }) => (
  <div>Hello</div>
)

Component.defaultProps = {
  prop1: {my:'prop'},
  prop2: ['My Prop'],
  prop3: ()=>{}
}

or

const defaultProps = {
  prop1: {my:'prop'},
  prop2: ['My Prop'],
  prop3: ()=>{}
}
const Component = ({
  prop1 = defaultProps.prop1,
  prop2 = defaultProps.prop2
  prop3 = defaultProps.prop3
 }) => (
  <div>Hello</div>
)

Shameless Plug here, I'm the author of with-default-props.

If you are a TypeScript user, with-default-props might help you, which uses higher order function to provide correct component definition with defaultProps given.

Eg.

import { withDefaultProps } from 'with-default-props'

type Props = {
    text: string;
    onClick: () => void;
};

function Component(props: Props) {
    return <div onClick={props.onClick}>{props.text}</div>;
}

// `onClick` is optional now.
const Wrapped = withDefaultProps(Component, { onClick: () => {} })


function App1() {
    // ✅
    return <Wrapped text="hello"></Wrapped>
}

function App2() {
    // ✅
    return <Wrapped text="hello" onClick={() => {}}></Wrapped>
}

function App3() {
    // ❌
    // Error: `text` is missing!
    return <Wrapped onClick={() => {}}></Wrapped>
}