learnreact.com is moving to school.reactpatterns.com. Get 50% off while we move.

Learn React

Learn React | <!-- -->Essetial React<!-- --> > <!-- -->Separation of Concerns with components

Essetial React

Separation of Concerns with components

An important topic in programming is always separation of concerns. Now this component here, this Pokemon component, legitimately has two concerns. First it knows how to fetch and store locally a Pokemon from the pokeapi. The second concern is it knows how to display that Pokemon, and also a loading state for it. In an ideal world, these two concerns would be separated and composed together. Let’s do that starting from the furthest point out, in. First, let’s rename this to FetchPokemon. That seems like a more appropriate name, given the fact that that’s what it’s doing, and then change the name of our component. Everything still works, so we’re in good shape to move on to the next change. Here we want to pull out this, and stick it inside of another component. We’ll name that Pokemon, now that the name is freed up. Let’s define this as a simple functional component, because we don’t need any of those special powers of state and life cycle methods. It’s a functions takes props and renders everything that we had before. Now, there are going to be changes because we aren’t using the state directly. We need to grab these values off of props, and in our FetchPokemon component we need to provide them these props. Everything works, but we’ve split out this concern of display. Now these separations go by many different names. They’re often called smart and dumb components, or data and display components. I just call them knowing and unknowing components. This component doesn’t know anything except for what it’s given, and this component has all of the “know how” to collect and store information. It knows things. Now in this point in our refactoring of these components, this is mostly cosmetic. We’ve separated the concerns, but there's still a coupling. This still only renders Pokemon. For this to be a completely generic component, one that’s reusable across our app, we need to decouple this rendering concern, and ideally both of these.



Keep in touch!

Get notified of new React content and resources

    We respect your privacy. Unsubscribe at any time.