Skip to main content

Command Palette

Search for a command to run...

React useContext Hook

Updated
1 min read
React useContext Hook

useContext is a built-in React hook that allows you to consume values that are provided by a Context object. A Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Here is a basic example of how to use useContext in a React component:

import React, { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";

export default function App() {

const MyContext = createContext();

function OuterComponent() {
  const [value, setValue] = useState('test');
  return (
    <MyContext.Provider value={value}>
      <h1>{`Hello ${value}!`}</h1>
      <InnerComponent />
    </MyContext.Provider>
  );
}

function InnerComponent() {
  return (
    <>
      <h1>Inner Component</h1>
      <NestedComponent />
    </>
  );
}

function NestedComponent() {
  const contextValue = useContext(MyContext);

  return (
    <>
      <h1>Nested Component</h1>
      <h2>{`Hello ${contextValue} again!`}</h2>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<OuterComponent />);
}

In the example above, we create a Context object . Then, inside the NestedComponent function, we use the useContext hook to consume the value provided by the MyContext context. The contextValue variable now contains the value passed in by the nearest <MyContext.Provider> higher up in the component tree.

You can use the useContext hook to consume values from multiple contexts in the same component. Just call useContext with each context object you want to consume.

More from this blog

R

Raja Muhammad Asher - Senior Software Engineer - Full Stack Developer

157 posts

Full Stack Developer with a passion for building web applications. PHP, Node.js, Laravel, ExpressJS, MySQL, MongoDB. Love collaborating & making a difference