Nearby lessons

19 of 44

⚛️ ReactJS – useContext Hook

📌 What is useContext?

What is useContext in React?

The useContext Hook allows you to share state across multiple components without manually passing props down through every level (known as prop drilling).

It works together with Context API and can be combined with useState to manage global state more efficiently.

📌 Why use useContext?

  • React Context is used for global state management.
  • Avoids prop drilling (passing props through every child).
  • Makes code cleaner and easier to maintain.
  • Works well with useState for updating shared data.

⚠️ The Problem Without useContext

Without Context, we need to pass props through each component manually.

This makes the code complex and repetitive, especially for deeply nested components.

React Playground
import React from 'react';
import ChildA from './ChildA.jsx';

const App = () => {
  const firstName = "Rajesh";
  const lastName = "Rathwa";

  return (
    <div>
      <ChildA firstName={firstName} lastName={lastName} />
    </div>
  );
}

export default App;

✅ Example – Using useContext

Let's create a simple app that shares a first name and last name across multiple nested components using Context.

React Playground
import React, { createContext } from 'react';
import ChildA from './ChildA.jsx';

export const FnContext = createContext();
export const LnContext = createContext();

const App = () => {
  return (
    <div>
      <FnContext.Provider value={"Rajesh"}>
        <LnContext.Provider value={"Rathwa"}>
          <ChildA/>
        </LnContext.Provider>
      </FnContext.Provider>
    </div>
  );
}

export default App;

🔄 With useState + useContext

We can also combine useState with useContext to update shared state dynamically.

React Playground
import React, { createContext, useState } from 'react';
import ChildA from './ChildA.jsx';

export const FnContext = createContext();
export const LnContext = createContext();

const App = () => {
  const [name, setName] = useState("Rajesh");

  return (
    <div>
      <FnContext.Provider value={name}>
        <LnContext.Provider value={"Rathwa"}>
          <ChildA/>
        </LnContext.Provider>
      </FnContext.Provider>
    </div>
  );
}

export default App;

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - Forms