Passing React Props: One by One or Group and Spread?

twitter logo github logo Updated on ・1 min read

Sometimes when I don't like passing props like example A (which IMO looks too verbose, especially if it's more than 2 props), I group into a new variable and spread props like example B.

Is there any downsides writing like example B? Should I stick with example A?


twitter logo DISCUSS (6)
markdown guide
 

eslint has a rule that doesn't allow spreading of props due to readability issues. You can read more about it here.

 

There is no downside in that as long as you are certain what the object you're spreading into the component looks like. In this case, it's easy to start passing things that the component doesn't even need, and introduce unnecessary rerenders.

 

So for example, if a component only needs A and B but C is also given, and if C is changed, it wil rerender?

 

That it would, yep. Also think about the contract of you component, so to say.
I think you are adding an additional, not necessary layer in the middle, the reading patterns of the code would be as following:

Component usage -> Wrapper Object definition -> Value definition

vs

Component usage -> Value definition

I am usually reluctant to bring in any indirection if it doesn't have great value to add to the code.

My 2 cents,
Ale

 

Exactly! Even if the component doesn't use that prop at all, it will still rerender.

 

Last week, there was a similar question on Reddit.

Passing props by spreading? Bad or doesn't matter? Saw some people say it can cause performance issues

My reply was

  1. It breaks encapsulation - Child component doesn't have to know about all props.
  2. It harms readability - Picking props makes it more intentional or what are you passing down?.
  3. It can break child component - Depending on where you spread, it can override child props.
  4. It breaks with ref - If child component doesn't use forwardRef, ref isn't passed down.
  5. It's lazy.

And also according to Awnry_Abe's reply

It also lets you slip invalid props past TS.

Classic DEV Post from Mar 19

Jack of the Stack

Different developer types described by the alphabet.

Griko Nibras profile image
Love working on web technologies like Laravel, Node, and React frameworks, especially Gatsby and Next.

😓 Sore eyes?

dev.to now has a dark version (in public beta).

Go to the "misc" section of your settings and select night theme ❤️