DEV Community

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

Posted on • Edited on

13 4 1

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.

// themeContext.js
import { createContext } from "react";
// initial state can be any primitive or non-primitive type
const initialState = "light";
// context object
export const ThemeContext = createContext(initialState);
// provider component
export const ThemeProvider = ThemeContext.Provider;
// consumer component
export const ThemeConsumer = ThemeContext.Consumer;
view raw ThemeContext.js hosted with ❤ by GitHub

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.

// index.js
...
import { ThemeProvider, ThemeConsumer } from "./themeContext";
const MyComponent = () => {
return (
// getting context value via ThemeConsumer component
<ThemeConsumer>
{theme => {
document.bgColor = theme === "light" ? "white" : "black";
document.fgColor = theme === "light" ? "black" : "white";
return <h1>useContext</h1>;
}}
</ThemeConsumer>
);
};
const App = () => {
return (
// setting context value via ThemeProvider component
<ThemeProvider value="light">
<MyComponent />
</ThemeProvider>
);
};
...
view raw index.js hosted with ❤ by GitHub

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.

// index.js
...
import { ThemeContext, ThemeConsumer } from "./themeContext";
const MyComponent = () => {
// getting context value via useContext Hook
const theme = useContext(ThemeContext);
document.bgColor = theme === "light" ? "white" : "black";
document.fgColor = theme === "light" ? "black" : "white";
return <h1>useContext</h1>;
};
const App = () => {
return (
// setting context value via ThemeProvider component
<ThemeProvider value="light">
<MyComponent />
</ThemeProvider>
);
};
...
view raw index.js hosted with ❤ by GitHub

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

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)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay