DEV Community

Discussion on: Is it true that components in a ReactJS app should be divided into container components and presentational components?

Collapse
 
sargalias profile image
Spyros Argalias • Edited

As you said, it is completely optional.

There are two reasons why you may want to separate into containers and presentational components:

  1. You can reuse either independently of the other.
  2. Apply the single responsibility principle (code is much easier and safer to work with).

Answer: Separate them if you want the benefits or if you just feel like it. Otherwise there is no reason to. Personally, I lean towards separating them.

In more detail:

Reuse components

If a view is dumb, it can be reused anywhere else in the codebase. You can even put it in an NPM package and use it in other codebases.

One example for this may be a different view for blog posts. Maybe you use the same container, but depending on user preferences or something you can have two different views for the blog posts.

Same with "container logic" (things like getting data and such). Using custom react hooks, you can put logic in there and import them in multiple different containers. This allows you to reuse logic.

For example you may have a single view for blog posts, but perhaps have two different ways you can obtain data for blog posts. Two different containers, which both use the same view.

Single responsibility principle

If logic and views are bundled together, then when modifying either one you could break the other. Also you are working with more code, so there is more to read and understand before you can change anything.

Separating them improves this.