Context API and useContext
Hello everyone, you may have heard of the Context API and the useContext hook separately many times. I will actually tell you the relationship and usage of these two definitions.
Firstly, Why you should use Context API?
You know that in React, props are passed to pass information from parent component to child component. But in a multi-component and complex related system, it becomes increasingly difficult to pass props. Because it needs to go through the components in between. This is called prop drilling.
The Context API is used to eliminate this problem.
For example, in this flow chart, when there is without Context API, it is necessary to pass the prop through the userProfile.js file in between, but when the Context API is used, it can be used directly in the file to be used without visiting the file or files in between.
So what steps do you need to perform to use it?
- Create a context
- Use that context from the component that needs the data.
- Provide that context from the component that specifies the data.
Create a context
First, you will create a context and export it.
You can use default value as an argument in createContext.
Use the context
Suppose you have a component that takes level and children.
To use context in this component, we need to define the useContext hook and our own defined context.
This is where the useContext hook comes into play.
The component to be used at the beginning was like this,
When the context imported:
In this way, since we define the level value as context, we can call it wherever we want.
🔗 useContext hook tells React that the LevelComponent component wants to read the LevelContext.
Provide the context
The Provider component helps wrap the components which have access to our context.
The Provider component receives a prop called “value,”, which can be accessed from all the components wrapped inside the Provider.
That’s it! You saw the Context API writing style and where the useContext hook is used.
Generally, the Context API is used in these operations:
- Authentication
- Theming
- Responsiveness
- User profile management
I hope I have informed you enough about Context API and useContext. See you in my next post.