Bipin Rajbhar
Posted on April 20, 2020
Hello, everyone π, I hope you are doing great π.
So, today you are going to learn all the fundamental concepts of useContext
Hook in this article.
Before you start, there are some rules you need to follow to use Hooks π. Thankfully the React Team has provided an ESLint Plugin called eslint-plugin-react-hooks that enforce these rules when using Hooks π€©.
Context
Context allows you to pass the data to the child deep down the tree without having to pass it through every component in between via props.
A trendy use case of context is theming.
There are only three steps you need to follow to implement context.
- Create a context object.
- Provide a context value.
- Consume a context value.
createContext Method
To create a context object, you need to use createContext
method.
The initial state is only used when the component does not have a matching provider.
The context object contains a Provider Component and a Consumer Component.
Provider and Consumer Component
The Provider Component is used to set the context value and a Consumer Component that is used to get the context value.
useContext Hook
You can use the useContext
Hook in the functional component to access the Context value.
If you use the useContext
Hook, you do not need to wrap it with a Consumer Component.
The useContext
Hook takes a Context object as an input and returns a Context value as an output.
Example
Now, you have learned all the fundamental concepts of useContext
Hook π€.
Thanks for reading! My name is Bipin Rajbhar; I love helping people to learn new skills π. You can follow me on Twitter if youβd like to be notified about new articles and resources.
Posted on April 20, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.