JS: React Hooks
Theory: useContext Hook
In React, we pass data from upper to lower levels. But this approach is inconvenient when we work with global data that is needed simultaneously in many components at different levels of the hierarchy.
Such data includes the current level or color scheme. It is not convenient to transfer such data directly; you have to drag it through the entire application. We can use a context mechanism to deal with it. It allows us to pass things to the application and get access to data directly in any component, bypassing props.
The useContext() hook allows you to use contexts inside the component. To do this, you need to perform three steps:
-
Initialize the context object in the same place where we initialized the application:
-
Connect the provider and pass the data to the context object via the
valueprop: -
Get the context object data:
Here is another example of a context object. We store the current topic in it:
And somewhere inside the application:
We can store both a primitive value and an object inside the context. React does not track changing the contents of this object and therefore doesn't trigger re-rendering.
But if you replace the object itself, React will know about the change because of the changed link and will redraw the components inside the provider.
Sometimes, we store dynamic data in the context — during authorization, for example. When the user logs in, we have to save some data to provide the user with additional functions.
The context doesn't provide anything for this, but you can pass methods for manipulating data to the context and store it using useState().
A more advanced option is to create a provider in a separate component. This way, we can isolate the data from the entire application and transfer the interface to the components to interact with the data.
To do this, create a context in a separate module so that all components can import it:
Creating a separate provider component:
And inside the application, we use the provider as a regular component:
In the component itself, you can now import the context object and use functions from the provider to change the state in the context:
Context is a convenient mechanism for certain situations, but it shouldn't become the default way to pass data around the application. This temptation appears for many who are using it for the first time. The main problem with context objects is that they bind components to global data, making it difficult to reuse them in other situations.

