Understand React useContext hook through example

May 28, 2020 Goodman Loading... Post a comment

The React Context API is useful for passing data (including number, object, function… ) 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.

Example

In this example, we will use the useContext hook to retrieve data passed from the top-level component to a grandchild component. We won’t care about CSS files, just focus on 4 ones: App.js, RootContext.js, components/Child.js, components/GrandChild.js.

Firstly, create a new React app:

npx create-react-app app_context_hook

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";

const data = {
  number: 123,
  text: "ABC",
  func: () => {
    alert("Hello!");
  },
};

function App() {
  return (
    <RootContext.Provider value={data}>
      <Child />
    </RootContext.Provider>
  );
}

export default App;

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

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

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

Child.js:

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

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

export default Child;

GrandChild.js:

import React, { useContext } from "react";

import RootContext from "../RootContext";

const GrandChild = (props) => {
  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

You should see something like this:

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. I’m more than happy to hear from you 🙂

guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x