36

Implementing the Container Pattern using React Hooks

 4 years ago
source link: https://blog.bitsrc.io/implementing-the-container-pattern-using-react-hooks-f490a8492d05
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Implementing the Container Pattern using React Hooks

How to use the useState hook to create a functional container component.

Dec 31 ·4min read

mm6NR3u.jpg!web

Photo by Vanessa Bucceri on Unsplash

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.

What are React Hooks?

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 .

What is a Container in Container Pattern?

“A container does data fetching and then renders its corresponding sub-component. That’s it.”

Jason Bonta

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 :

3Q7vQjU.png!web

The list component has no logic of its own and has a clear and explicit API, making it very easy to reuse:

QFfUVzZ.jpg Example: Shared “dumb” component in a collection in bit.dev

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK