DEV Community

Discussion on: Write Better Frontend Components with This Tip

Collapse
 
tahazsh profile image
Taha Shashtari

I would avoid using the presentational-container pattern as the main way to design my components.
But I would use it in those cases when I have some UI component that can be rendered using a different set of data based on the current page or the current state of the app.

Let's say, for example, you have a UI component (presentational component) that displays a chart that describes how posts are doing in your blog. This chart component can take a single post or a set of posts. Let's say that in some places you would use this chart to display how your latest post is doing, but in other places, you want to show how your team's latest posts are doing.

Assuming that you want to display each type of chart in multiple places, you would end up duplicating the logic of fetching your latest post and your team's latest posts each time you need to display that chart. What you can do instead is creating a container component for both chart types, and in each one, you would include the needed logic to fetch and format the posts before displaying them in the chart.

So if you want to display your-latest-posts chart in the sidebar and in the main section of the page, you would just do something like this:

<sidebar>
  <MyLatestPostChart/>
</sidebar>
<main>
  <MyLatestPostChart/>
</main>

As you can see, you don't have to rewrite how to fetch those posts, because it's already done in the container component. (btw, you don't have to add the suffix Container to it — name it whatever you want.)

So in conclusion, this pattern is like any other pattern, use it when you need it. And don't try to follow the rules of that pattern strictly. So it's fine if you need to pass props to the container component.

I hope this clarifies things for you. Please don't hesitate to ask further questions :).