JS: React
Theory: Context API
Passing data down the component hierarchy via props is a wordy but straightforward mechanism. You can always see where the data came from and how it got in, and the components are easy to reuse because they depend only on the input data. But there are situations where passing props doesn't match how the code works.
Let's take a hypothetical current user as an example. Often, user data is needed in different parts of the page and deep components simultaneously. To do this, you should pass the user all over the hierarchy, even where the component doesn't need it.
The only purpose of such a transfer is to send the data to its destination, passing all the intermediate components along the way.
It turns out that many components do not use the user in any way. They only pass them on down the chain. The user's data, in our situation, are global. Several components at different levels of the hierarchy need them at once. There is, however, a workaround for such tasks in React.
The Context API is a mechanism for making global data available from any component directly, without props. Its use boils down to three steps:
-
Creating the context:
-
Transferring data into the context. We wrap the required components in a context component
<UserContext.Provider>and pass the required data there in thevalueprop: -
Getting data from the context in the right place:
Unlike props, changing the data in the context does not result in a redraw by default. It's ideal when the data in the context is read-only. It's better to store modifiable data inside component states. However, if you need to, it is possible to respond to a change of context. You can read more about this in the documentation.
Programmers rarely use this feature in application code but write various libraries with it.

