DEV Community

Cover image for React Tricks Miniseries 5: How to pass props more efficiently
Uriel Bitton
Uriel Bitton

Posted on

React Tricks Miniseries 5: How to pass props more efficiently

React is all about props and the more you use reusable components, the more scaleable your react app will become (if done correctly, of course).

Passing props to a child component may be trivial, but many developers do it wrong. We've all been there though. Most of use pass props in one of two way. Either passing every property we wish to use, or passing an object containing the props we want to use.

Method 1

<Card 
  cardObject={cardObject}
/>
Enter fullscreen mode Exit fullscreen mode

Method 2

<Card 
  title={title}
  description={description}
  rating={rating}
/>
Enter fullscreen mode Exit fullscreen mode

With the first scenario, we'd need to retreive the props inside the Card component, in a less than efficient way:

export default function Card(props) {
  const { title, description, rating } = props.cardObject
}
Enter fullscreen mode Exit fullscreen mode

And with the second scenario, when the list of props gets long, it becomes too inefficient to add them all one by one.

Solution

The best practice method is to use object destructuring like this:

<Card 
  {...cardObject}
/>
//then retrieve the props in the usualy way
export default function Card({ title, description, rating }) {

}
Enter fullscreen mode Exit fullscreen mode

This method is a lot cleaner, more efficient and scales much better for long lists of props.

Conclusion

Using object destructuring, we can achieve better and more efficient props passing to react components.

Have you always used this method? Or just learned it now? Let me know in the comments!

Top comments (0)