DEV Community

Cover image for State Management in Pure React: useContext Hook
Bipin Rajbhar
Bipin Rajbhar

Posted on • Edited on

State Management in Pure React: useContext Hook

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.

  1. Create a context object.
  2. Provide a context value.
  3. 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.

Top comments (1)

Collapse
 
lalami profile image
Salah Eddine Lalami

@ IDURAR , we use react context api for all UI parts , and we keep our data layer inside redux .

Here Article about : 🚀 Mastering Advanced Complex React useContext with useReducer ⭐ (Redux like Style) ⭐ : dev.to/idurar/mastering-advanced-c...


Mastering Advanced Complex React useContext with useReducer (Redux like Style)