Single Responsibility Principle (SRP) In React: Write Focused Components
A practical look at applying Single Responsibility Principle into React. (3 minutes)
Some time ago I shared an article about the SOLID Principles, and how we can write a more robust and maintainable code by applying them.
From a theoretical perspective, if you ask less experienced engineers about SOLID, everything is “okay”.
However, when it comes to applying SOLID, things start to get a bit harder.
In today’s article, I’d like to share a more practical look at applying the Single Responsibility Principle (SRP) into React.
What is the Single Responsibility Principle (SRP)?
By definition, the principle states:
”A class should only have one reason to change.”
In other words, a class, function, or module should have a single responsibility.
You can read more about the Single Responsibility Principle (SRP) in my previous article.
Violating the Single Responsibility Principle (SRP) in React
Let’s first see how things look like when we violate the SRP in React and write not so good enough components.
The problem with this component is that it:
handles data fetching for the products
manages the loading and error states
handles the form for adding a new product
takes care of the display and layout of the products
The ProductsDashboard Component has four reasons to change which makes it harder to understand, maintain, debug, test, and reuse.
Be the Senior who delivers the standard for writing robust React Components.
Write Better Components by Separating Concerns
A better alternative is to split all these responsibilities and reasons the component to change into separate focused components.
1. Use Custom Hook for Data Fetching, Loading, and Error Handling
2. Use a Separate Component for the Form
3. Use a Separate Component for Displaying the Products
4. Use a Separate Component to Handle the ProductsDashboard’s Logic
📋 Recap
Separate data handling from User Interface.
Use custom hooks for data fetching and/or business logic.
Write small and focused components, doing only one thing, and do it well.
Prefer composing a set of smaller components, instead of writing big ones.
Organize your components in terms of layers: hooks, guard clauses, main render, smaller components, etc.
That's all for today. I hope this was helpful. ✌️
👋 Let’s connect
You can find me on LinkedIn, Twitter(X), Bluesky, or Threads.
I share daily practical tips to level up your skills and become a better engineer.
Thank you for being a great supporter, reader, and for your help in growing to 18.3K+ subscribers this week 🙏
You can also hit the like ❤️ button at the bottom to help support me or share this with a friend. It helps me a lot! 🙏