Your React Components Are Doing Too Much

Travis Waith-Mair
Non-Traditional Dev
4 min readJan 24, 2019

--

Photo by Markus Spiske on Unsplash

Components are the building blocks of React. They are the legos that let you build your app, piece by piece. Components can be huge or small. Just Like legos, bigger components are more difficult to work with. The more your component is concerned about, the harder it is to use and maintain in your app.

Let’s take this ClickerCounter component for example:

It’s not a very complicated component. You click on the span and the count increments, click on the button and it resets. It also changes to a dark theme if the dark prop is passed. Despite the fact that it’s not a complicated component, it is doing too much. In Robert Martin’s book Clean Code, he recommends that functions should do one thing, do it well, and do it only. Our component is not following this principle. How do we fix it?

Separate State Management

The easiest and most obvious concern that you can factor out is state management. The JSX in the render doesn’t technically care how the count is updated, all it really needs to care about is that it updates. Here is one way to do that:

--

--