DEV Community

Cover image for Introduction to React Context API
vidhi-thakur
vidhi-thakur

Posted on • Updated on

Introduction to React Context API

hello

What is React Context API?

React Context API is a React API that allows one to share state across an entire app. Instead of installing a state management library in your project or prop drilling, the React Context API provides a way for a React app to effectively produce global variables that can be passed around.

Diagram

createContext hook: -

React hook that is needed for this purpose is createContext(). It returns a provider and a consumer. The provider, as the name suggests, provides a state to its children whereas the consumer uses the state.

Example 1: -

import React, { createContext } from "react";

// creating a context
const StateContext = createContext();

export default function App() {
  return (
    <StateContext.Provider value={56}>
      <ShowValue />
    </StateContext.Provider>
  );
}

function ShowValue() {
  return (
    <StateContext.Consumer>
      {(value) => <p>The display value is: {value}.</p>}
    </StateContext.Consumer>
  );
}
Enter fullscreen mode Exit fullscreen mode

To see the working implementation of the above example, click here.

In the example above, we created a context. Now think of creating a context as creating a data layer. After the context is created, we wrapped a component (i.e., ShowValue component) in the data layer so that the data or value is accessible in that component. Finally, the data (or value) is fetched using the consumer. Note that the consumer obtains the value passed by the provider without prop drilling.

Using react Context API lets you avoid passing of props from parent component to children components. It's all good until you need to pass multiple values. In case of retrieving data from multiple parent contexts, a lot of nesting is introduced.

<CurrentUser.Consumer>
      {user =>
        <Notifications.Consumer>
          {notifications =>
            <header>
              Welcome back, {user.name}!
              You have {notifications.length} notifications.
            </header>
          }
        </Notifications.Consumer>
      }
    </CurrentUser.Consumer>
Enter fullscreen mode Exit fullscreen mode

Therefore, to make the code less verbose we use useContext() hook.

useContext hook: -

The useContext() hook provides a way to pass the data or value to any component without using the consumer. Further, it makes the code more readable and reduces cognitive overhead (i.e., the used amount of working memory resources).

With useContext() hook, the code in example 1 will look like this: -

import React, { createContext, useContext } from "react";

const StateContext = createContext();
const useStateValue = () => useContext(StateContext);

export default function App() {
  return (
    <StateContext.Provider value={56}>
      <ShowValue />
    </StateContext.Provider>
  );
}

function ShowValue() {
const value = useStateValue();
  return (
      <p>The display value is: {value}.</p>
    );
}
Enter fullscreen mode Exit fullscreen mode

To see the working implementation of the above example, click here.

Note: To further manage the state of the app, useReducer() hook is used.

Conclusion

By using React Context API, we can produce global variables that can be passed around an entire application and avoid prop drilling. For this purpose, the createContext and the useContext hooks are used. In addition, the useReducer hook can also be used in the case of managing the state of the app.

P.S. Context API should only be used when you need to share state between many components with a lot of nesting.

Top comments (0)