React Tricks Miniseries 5: How to pass props more efficiently
Uriel Bitton
Posted on May 5, 2022
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}
/>
Method 2
<Card
title={title}
description={description}
rating={rating}
/>
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
}
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 }) {
}
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!
Posted on May 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.