loading...
Cover image for State Management in Pure React: useContext Hook

State Management in Pure React: useContext Hook

bipinrajbhar profile image Bipin Rajbhar Updated on ・2 min read

State Management in Pure React with Hooks (5 Part Series)

1) State Management in Pure React with Hooks: useState 2) State Management in Pure React with Hooks: useEffect 3) State Management in Pure React with Hooks: useReducer 4) State Management in Pure React with Hooks: useCallback and React.memo 5) 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.

State Management in Pure React with Hooks (5 Part Series)

1) State Management in Pure React with Hooks: useState 2) State Management in Pure React with Hooks: useEffect 3) State Management in Pure React with Hooks: useReducer 4) State Management in Pure React with Hooks: useCallback and React.memo 5) State Management in Pure React: useContext Hook

Posted on Apr 20 by:

bipinrajbhar profile

Bipin Rajbhar

@bipinrajbhar

I love to share every thing that i have learned

Discussion

markdown guide