Recently I’ve adopted a new philosophy that changes the way I make components. It’s not necessarily a new idea but rather a subtle new way of thin

How the “Golden Rule” of React components can help you write better code

submited by
Style Pass
2021-05-24 15:00:08

Recently I’ve adopted a new philosophy that changes the way I make components. It’s not necessarily a new idea but rather a subtle new way of thinking.

Which is pretty straightforward — solely looking at what it needs to function, you just need a name, job title, and picture URL.

But let’s say you have a requirement to show an “official” picture depending on user settings. You might be tempted to write an API like so:

It may seem like the component needs those extra props to function, but in actuality, the component doesn’t look any different and doesn’t need those extra props to function. What these extra props do is couple this preferOfficial setting with your component and makes any use of the component outside that context feel really unnatural.

We’ve adopted a folder structure where every component goes into a self-titled folder where the index file is responsible for bridging the gap between your “natural” component and the outside world. We call this file the “container” (inspired from React Redux’s concept of “container” components).

Leave a Comment