Skip to Main ContentSkip to Footer

React Global Component With Hooks

October 29, 2019

When Should You Use useContext?

Context or useContext is primarily used when some data needs to be accessible by many components at different nesting levels. If you want, for example, to manage a state used across your hierarchy without having to explicitly pass the prop, useContext will be great.

Some examples could be a state manager for your online or offline status; many components will need to access this info to show a fallback UI or manage a centralized notifications or messages system.

How Do You Use useContext?

You have to use two different Hooks. The first one is createContext to build the context inside a variable, in our example, AppStateContext.

After that, you will be able to declare your AppStateProvider with functions and states related to its inner functionalities.

In the render, you will wrap the AppStateContext.Provider, passing it the variables created inside the AppStateProvider.

How Do You Add the Context to the App?

You just need to wrap the components inside AppStateProvider to be able to use the Context on all children of the AppStateProvider.

It’s the same behavior as the Apollo client provider, which you can try in this article.

How Do You Access the Context?

Inside all the components where you need to use the Context, you will have to use the other, most important Hook, useContext! Passing it the AppStateContext.

After that, you will be able to access the values passed to the context. In this case, we have the functions SetMessage and SetError to manage all the notifications of our app in a centralized way.

You can also import only the values you need from the Context.

Complete CodeSandbox of This Tutorial

If you want to learn more about Hooks

I have personally read Learn React Hooks when I started using hooks and it helped me understand them to use tools such as useContext:

References and Resources

Subscribe to my email list!

If you enjoy my work, you should definitely join my newsletter"Giorat Mails". It’s one email a week with everything interesting I’ve read or found, plus new articles and fresh tutorials.

Sign up for our newsletter