Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

269
Views
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>
)    
10 months ago · Santiago Trujillo
3 answers
Answer question

0

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.

10 months ago · Santiago Trujillo Report

0

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.

10 months ago · Santiago Trujillo Report

0

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>
)
10 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.