When Should You Use useContext?
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,
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
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
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
After that, you will be able to access the values passed to the context. In this case, we have the functions
SetError to manage all the notifications of our app in a centralized way.
You can also import only the values you need from the