Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React props: Should I pass the object or its properties? Does it make much difference?

When passing props should I pass the entire object into the child components or should I individually create props first in the parent component and then pass those props to the child?

Pass entire object:

<InnerComponent object={object} /> 

Individually create props that're needed first:

<InnerComponent name={object.name} image={object.image} /> 

Which one is preferred and if it depends, what should I use as a gauge to use either?

like image 200
catandmouse Avatar asked Oct 03 '18 06:10

catandmouse


People also ask

Should you pass objects as props in React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component.

Why should you avoid copying the values of props into a component's state?

Anti-pattern: Unconditionally copying props to state Because of this, it has always been unsafe to unconditionally override state using either of these lifecycles. Doing so will cause state updates to be lost.

How many props are too many React?

I follow this rule of thumb: Three props is fine. Five props is a code smell. More than seven props is a disaster.

What is the purpose of the key prop used in React so that it can efficiently identify the changes in browser DOM?

React's key prop gives you the ability to control component instances. Each time React renders your components, it's calling your functions to retrieve the new React elements that it uses to update the DOM. If you return the same element types, it keeps those components/DOM nodes around, even if all the props changed.


1 Answers

You should prefer your second example, to pass the props individually. There you can see explicitly which arguments are passed and can quickly compare with which arguments are expected. This makes collaboration along people much easier and makes the state of the application more clear.

I personally try to avoid passing whole objects if it's not needed. It's like the spread operator where there can be any property inside and it is much harder to debug in a bigger scope.

Some additions to pure react like prop-types or typescript might help to define clear and expected properties in a big application

like image 139
mstruebing Avatar answered Sep 18 '22 07:09

mstruebing