This video is available to students only

Data fetching - Container Pattern

Using a container pattern to deal with complex components.

Suppose you have a stateful component that handles everything on its own: It requests data and renders a loading state while it's happening, and once the back-end returns data, it renders a successful state:

The container pattern#

The container pattern, also known as dumb/smart components, is a way to separate a complex component into two pieces:

  • One that does the business logic and data fetching (container),

  • and another one that only cares about UI (presentational component).

The container component passes the data down as props to the presentational component, and in case of interactions (e.g. clicks), the presentational component ouputs them to the container component. By detaching logic from certain components, you make it easier to reuse them in different use cases. This might help build component libraries, for instance.

Thinking on the context of the RestaurantsSection component we made in previous lessons, here is a simplified example of how it would look using a container pattern:

In this case, as the UI is isolated in a presentational component, it's relatively simple to add that component to Storybook: you would just export that presentational component and use it in your stories and it would be fully controllabe by the props it receives, like the simple components Badge and Review we made in previous lessons. We will see more about that in just a moment when exploring the example code for this lesson!

Given that the presentational component will always render the same result if the same props are passed, it is considered a Pure Component. This allows us to use tools like React.memo to memoize the component if we want!


This page is a preview of Storybook for React Apps

Start a new discussion. All notification go to the author.