Context in React
Before we move on to the next hook, we need to cover the concept of context in React.
Traditionally, we passed data from parent components to child components using props. This is a good way if you have a small number of components and you don't need to pass props from parent to the component you need through children more than 2-3 times.
This method can also become extremely inconvenient and lead to various problems if the intermediate components do not use these props at all (this problem is called prop drilling), or you need to pass the same data to a large number of components.
In these cases, context can help us, which allows us to make the data of the parent component available to any child, regardless of its location in the component tree, without passing it through props. Accordingly, only those components that need it will receive the data.
In order to use the context, you need to create it. First, let's create a file MyContext.js and import the function createContext into it:
import { createContext } from 'react';
Now let's create a context object, write it to the variable MyContext, which we won't forget to export. In our case, we set the initial value null in createContext, since it is not important to us (we could have left the brackets empty). The specified default value will appear when reading the context if no other values are found. This value can be of any type:
export const MyContext = createContext(null);
In the next lesson, we will create an application from several components located in separate files. If all the components were in one file, then we would not create a separate file to create the context and would not export it.
Let's now import MyContext.js into the empty component App - the component from which we are going to pass data:
import { MyContext } from './MyContext.js';
Create a file MyContext.js and import it into the empty App component as described in the tutorial.