loading...

Writing (clean) React code

Jithin KS on March 11, 2020

Building simple software We generally think that building complex software is hard. But the hardest thing is building complex software i... [Read Full]
markdown guide
 

Wrapping props in an object is risky business. You have to understand well how that particular prop travels down the components and where it is created and how often updated. Otherwise you'll make your app do unnecessary updates and re-renders which may impact the performance significantly.

 

Yeah, I think that is true. I'm not saying that you mindlessly combine every props into an object. Props that are really related to each other can be combined into an individual unit.

I can give you an example. Suppose that there is a Shapes component that renders a line and a circle.

const Shapes = (props) => {

  // Here we destructured the respective parameters child components want
  // And passing to the components

  const { lineParams } = props
  const { circleParams } = props

  // Line and circle rerender only if their respective props change

  return (
    <>
      <Line params = {lineParams}/>
      <Circle params = {circleParams}/>
    </>
  )
}
const Shapes=(props) => {

  const { combinedParams } = props

  // Here we have mindlessly combined everything into one
  // So whenever it changes both will rerender which we do not want

  // Props that are combined should be taken out
  // at appropriate levels

  return (
    <>
      <Line params={combinedParams}/>
      <Circle params={combinedParams}/>
    </>
  )
}

<Shapes
  lineParams={lineParams}
  circleParams={circleParams}
/>

I'm just saying that the above is better than the component below :

<Shapes
 lineX1={lineX1}
 lineY1={lineY1}
 lineX2={lineX2}
 lineY2={lineY2}
 circleX={circleX}
 circleY={circleY}
 circleRadius={circleRadius}
/>
 

Creating objects and passing them as props directly in the render function is a bad practice.
For example, this

<Circle
 center={{x,y}}
 radius={radius}
/> 

will rerender <Circle> component on each render.

 

OK, it should be

// Circle renders if center or radius changes
<Circle
  center={center}
  radius={radius}
/>

Thanks for pointing out

 

Simple post, but gold. I liked it.

 

A really good compilation of all the learnings we have acquired while working with React. Very useful!

 

All of these are πŸ”₯! Thanks for the article!

 

If the prop is the same name as the variable, please, do this:

const data = []
return <Component {... { data } } />
 

Hi,

What benefits will give us by wrapping data array inside the object literal?

 

Great read for newbies like me, thank you! πŸ™πŸ»

 

Another big gain in the point 4 is avoiding new memory allocation for the functions each render.

 
code of conduct - report abuse