Single Responsibility Principle

First is the Single responsibility principle. This principle tells us that module should have one and only one reason to change.

Let’s imagine we are trying to build an application which displays users in a table.

We have a component which has a user list in the state. We are fetching users from some HTTP endpoint and each user is editable. This component violates the Single Responsibility Principle because it has more than 1 reason to change.

I can see these reasons.

Every time I want to change the header of application. Every time I want to add a new component to the application (e.g. footer). Every time I want to change the user fetching mechanism, for example, the address of endpoint or protocol. Every time I want to change the user list table (e.g. column styling, etc…)

Solution. After you identify your reasons to change try to eliminate them by creating a suitable abstraction (component, function, …) for each reason.

Let's try to fix that problem. Lets go refactor the App component.

Now, when we want to change the header we change the Header component and when we want to add a new component we change the App component. We solved problem 1 (change the header of application) and 2 (add a new component to the application) by moving that logic from the App component to the new components. Let's solve the problem 3 and 4.

This is our new container component UserList. We solved problem 3 (change the user fetching mechanism) by creating props functions fetchUser and saveUser. So when we want to change the HTTP endpoint we go to the function (save/fetch)User and change that there.

The last problem 4 (change the user list table) was resolved by creating a simple presentation component UserTable which encapsulated the HTML and styling of the user table.