React Providers and Where to use them

Igor Imperiali Fernandes
hurb.labs
Published in
2 min readApr 8, 2021

A simple way to understand the React providers and how to use them

Man pet an gigant bird

In many times when we are coding, we get to the situation where the data must be passed from parents to the children, and can look like this:

And there is no problem with this component, right? But… What if our component Child uses some kind of data that the Parent is the one who acquires him? Maybe something like this:

And what if the parent has another child…

The Parent is the one who can acquire the toys for the Child, but he is not using it… He is just providing it… (get it?)

So, in cases like this, we may want to create a Provider, to acquire those data and let them be accessed from outside…

This looks ok to you? Imagine that… The Parent is the one who acquires the toys, but now it is no longer the one who Provide them.

Well… But how the hell we access those toys in the Provider?!

An easy and elegant way is access them by a Hook!

See, in this way, we can separate the responsibility, so the component does not have to deal with what they don’t use… Make’s sense? 🤔

That said, let’s see how the Provider and the Hookshould look like.

We have here a new guy, the famous Context , for the propose of this post, let’s say that the Context is the “toy box” where the Child can have access to the toys.

And this is the Hook that the Child will use to access the toys!

Notice that the Hook is the one who accesses the context, them, if we decide to enable the possibility to add new toys, for example, we could do this in the hook, but that’s another talk… Maybe?

--

--