Working with the useContext hook in React

Updated: February 13, 2023 By: A Goodman 2 comments

Introduction

The React Context API is useful for passing data (including numbers, objects, and functions… ) deeply throughout a React app. It makes your life much easier than using multi-level props.

The useContext hook is available in React 16.8 and newer versions. It accepts a context object and returns the current context value for that context. In most small and medium web applications, you can use context for state management instead of complex approaches like Redux or Mobx.

Example

App Preview

In this example, we will use the useContext hook to retrieve data passed from the top-level component to a grandchild component. This data includes a number, text, and a function.

The Steps

We won’t care about CSS files. just focus on 4 ones: App.js, RootContext.js, components/Child.js, and components/GrandChild.js:

.
├── App.js
├── RootContext.js
└── components
    ├── Child.jsx
    └── GrandChild.jsx

1. Firstly, create a new React app:

npx create-react-app app_context_hook

2. Delete all the code from App.js and add the following code:

import React from "react";

import Child from "./components/Child";
import RootContext from "./RootContext";

// This object will be passed to the GrandChild component through context
const data = {
  number: 123,
  text: "ABC",
  func: () => {
    alert("Hello!");
  },
};

function App() {
  return (
    // RootContext Provider
    <RootContext.Provider value={data}>
      <div style={{ padding: 30 }}>
        <Child />
      </div>
    </RootContext.Provider>
  );
}

export default App;

3. Create a file called RootContext.js in the same directory as App.js:

// RootContext.js

import { createContext } from "react";
const RootContext = createContext();
export default RootContext;

4. Create a folder called components, then create 2 new files: Child.js and GrandChild.js.

Child.js:

// components/Child.jsx

import React from "react";
import GrandChild from "./GrandChild";

const Child = (props) => {
  return <GrandChild />;
};

export default Child;

GrandChild.js:

// components/GrandChild.jsx

import React, { useContext } from "react";

import RootContext from "../RootContext";

const GrandChild = (props) => {
  // useContext hook
  const data = useContext(RootContext);
  
  return (
    <>
      <p>{data.number}</p>
      <p>{data.text}</p>
      <p><button onClick={data.func}>A Button</button></p>
    </>
  );
};

export default GrandChild;

Run your app:

npm start

Conclusion

I hope the simple React example mentioned in this article will help you understand the useContext hook better in some way. If you have any questions about this topic, feel free to leave a comment. If you’d like to explore more new and interesting things in the modern React world, then take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
Ayodeji Oladapo
Ayodeji Oladapo
1 year ago

This is a great explanation.
I 100% have the basic knowledge now after going through so many documentations.

Thank you.

Related Articles