DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on

useContext in React

What is useContext: This is a hook that lets you to access data from a context without having to pass props manually. It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.

Syntax:

const value = useContext(MyContext);

Enter fullscreen mode Exit fullscreen mode

In React, Context acts like a global variable that can be shared across multiple components in an application.
A common use case for the Context Hook (useContext) is managing globally accessible data — such as the preferred theme (light or dark mode) or the currently logged-in user. You should use the Context Hook only when certain data needs to be accessed by several components throughout your app.

Ex:

import { useState, createContext, useContext } from 'react';
import { createRoot } from 'react-dom/client';

const UserContext = createContext();

function Component1() {
  const [user, setUser] = useState("Linus");

  return (
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 />
    </UserContext.Provider>
  );
}

function Component2() {
  return (
    <>
      <h1>Component 2</h1>
      <Component3 />
    </>
  );
}

function Component3() {
  const user = useContext(UserContext);

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

createRoot(document.getElementById('root')).render(
  <Component1 />
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)