As a developer, you have most likely come across the single responsibility principle when learning how to code. As a rule of thumb descendant from object-oriented design, it’s crucial in order to create reusable and flexible code, as well as the organizational and ‘DRY’ benefits that come with it.
What is the Single Responsibility Principle?
This means that every class should only have one responsibility — in other words, a class needs to have only a single job or a purpose for changing. If done properly, it allows us to reuse different classes and their unique properties across different areas of the application, without constantly rewriting the same code. On the other hand, having too much responsibility within a class makes it more difficult to reuse, as well as the possibility of causing unexpected behavior when running the application.
React naturally allows you to accomplish this by the idea of components — after all, we love React for doing just that, which is creating small and clean components to result in a beautiful and dynamic interface! You have the option of using class components or functional components, but we can implement this idea of SRP within the separate components.
While organizing your code, most importantly your components, the SRP may seem difficult to do at times due to the state and ensuring that it’s in the most common parent component (also known as state hoisting). In this case, you may have multiple functions that need to be hoisted within the same parent, in turn creating a large and possibly confusing component that is doing the job of multiple components at once.
… but this is where the single responsibility principle comes in handy!
Thankfully for React users, React makes it very simple to import different JS files in whichever component you are currently working on.
Instead of having a a parent component, or any component for that matter, hold multiple functionalities (state management, ui functionality, data filtering, initial data fetching), it’s best to separate them and import them into the parent component, and call the function in there.
Let’s say you are trying to create a small mock-up of a social media site, and your main functionality all needs to be hoisted to the ‘App’ component since it’s a common parent for the other components that need to utilize that info. ‘App’ needs to fetch the initial data, render the data onto the page with styling, and filter the proper data that needs to be rendered. If necessary, you can create the components as custom hooks in order to further simplify the data fetch.
The single responsibility principle is crucial across most object oriented languages, and a fifth of the SOLID principles used in software development.