Jake Worth

Objects as Props

Published: June 27, 2022 2 min read

  • javascript

A common frontend pattern is to pass an object as a prop. Consider an Avatar component that shows a user’s initials. What data should we pass to achieve this? The initials? The first and last names of the user? Or, should we pass the entire user object?

Let’s consider the tradeoffs of each.

Passing the Initials

We could pass just the initials.

<Avatar 
  initials={user.firstName[0] + user.lastName[0]} 
/>

The advantage of this approach is that the component gets what it needs– the initials– and nothing else. It lets the component to be dumb: “I receive a string ‘JW’ and I show it.”

Passing the Names

We could also pass the names that comprise the initials.

<Avatar 
  firstName={user.firstName} 
  lastName={user.lastName} 
/>

The advantage of this approach is that we aren’t manipulating data in the parent, but instead sending down what we need to the component and letting it build the initials.

Passing the Object

We could pass the entire object.

<Avatar 
  user={user} 
/>

This approach is forward-thinking. Very often the component will end up needing more pieces of the user, such as a full name to show as a title or a background color that the user has selected. Passing the object could be pragmatic.

Passing Multiple

We could also pass multiple of these.

<Avatar 
  initials={user.firstName[0] + user.lastName[0]} 
  user={user} 
/>

Components can drift into this pattern over time, and it’s the only really indefensible choice in this list. Passing an object and a string derived from it is redundant. It forces both the parent and the child to be smart about the object.

Conclusion

Which would I choose? I’m partial to passing the object. Practically, Avatar almost always ends up needing more pieces of the user. I think the pragmatic choice is to concede that from the start.

YAGNI is a counterargument, and I’m sympathetic because I’d love for every component to be dumb. However, often you are going to need it.

Reusability is another counterargument. What if we want to pass pieces of different kinds of objects to the component? Initials-only supports this. I think this aspiration is discussed more than it is realized in production code, but it could be the right choice.

Thanks to Gabe Reis who shaped my thinking on this during a year of building frontends together at Hashrocket.

🎉 Update: Adam Young responded to my post! He brought up some excellent points: how initials could be built in the ‘M’ of MVC, why displaying them can be a hard programming problem, and how to do it well.

✉️ Get better at programming by learning with me. Subscribe to Jake Worth's Newsletter for bi-weekly ideas, creations, and curated resources from across the world of programming. Join me today!


Blog of Jake Worth, software engineer in Maine.

© 2022 Jake Worth.