Before we dive into implementing Container Pattern using React Hooks, let me get you up to speed and briefly explain what React Hooks and Container Pattern are.
React Hooks let you manage state, as well as component lifecycle, in functional React components. That effectively makes everything functional and arguably, even eliminates the need for using class-based components.
To demonstrate how React Hooks work, here’s a basic example:
For more information about React Hooks, you can refer to React’s official website.
“A container does data fetching and then renders its corresponding sub-component. That’s it.”
Container Pattern is commonly used to separate data fetching/logic, events, and state from presentational components (aka, dumb components).
This can be particularly helpful if you want to reuse your presentational components in other use-cases, in your current project/codebase or in other projects. Keeping your components “dumb” makes it much easier to share and reuse them. For example, let’s say I want to share, using Bit (Github) the
list component from this app:
The list component has no logic of its own and has a clear and explicit API, making it very easy to reuse:
To explain how it works — see another example:
So, the code snippet demonstrates how to implement Container Pattern within your React components. On container component, it contains state, event handlers, complex logic, ajax calls, and renders presentational component.
On presentational component you’ll see UI stuffs mostly and the props that needs to be displayed in UI.
I have seen that Container Pattern is commonly used when you really want to separate state from presentational components. So, in this article, we will teach you just that but this time using React Hooks to manage state in a Container Component.