DEV Community

JRIVERADDIAZ
JRIVERADDIAZ

Posted on

Provider pattern.

The provider pattern is one of the most basic patterns that allows understanding the context API on react and use context hook, sometimes is very hard to implement cause is weird if you are a beginner, the basic trouble here is that the props heritage is too hard to maintenance if you are making a UI that have to use the info stored on it, also if some data is needed on all the app we can make it using this pattern that is the main purpose.

code-example-props

As you can see in this image the props have passed through the children of this component and if this is spread along the app using a component stack will be hard to understand the code.

props-context-diagram

In this diagram, you'll see the props are passed through the parent down to the children and the context that is on the app sharing the info all around the app.

The context is just there, you have to call it and the code is clear than using props a plus is that you can mutate the state.

As you can see on this image we are using the context, that is included on the react.js create react app or create vite

We have to make create a context wich can be (bollean, objetcs, arrays, numbers, string) that will be propagated all around the app.

basic-context-structure

We need to use the children, this allow us to wrap the information from the context all around the app, and make the context callable usign the useContext() hook.

context-structure

Now, this is an example, in a common react.js component.

useContext-usage

How, we are making a request to the global context, using useContext hook.

This allow us to make it out and get the info stored on it

Top comments (0)