logo
React Hooks - Interview Questions and Answers
What is useContext?
* useContext Hook in React

The useContext Hook is used to access values from React’s Context API without needing to wrap components in Consumer components. It helps manage global state efficiently by avoiding prop drilling.


Why Use useContext?
  • Eliminates prop drilling (passing props through multiple components).
  • Makes state accessible globally without lifting state up.
  • Improves code readability by reducing unnecessary wrapper components.

How to Use useContext?
1. Create a Context

First, create a context using createContext().

import { createContext } from "react";

const ThemeContext = createContext("light"); // Default value

2. Provide a Value with Provider

Wrap your components inside a Provider to supply the context value.

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ChildComponent />
    </ThemeContext.Provider>
  );
}

3. Consume Context with useContext

Instead of using <ThemeContext.Consumer>, we use useContext().

import { useContext } from "react";

function ChildComponent() {
  const theme = useContext(ThemeContext); // Access context value

  return <p>Current Theme: {theme}</p>;
}

Full Example
import React, { useContext, createContext } from "react";

// 1 Create Context
const ThemeContext = createContext("light");

function ChildComponent() {
  // 2 Use useContext to get the value
  const theme = useContext(ThemeContext);
  return <p>Current Theme: {theme}</p>;
}

function App() {
  return (
    // 2 Provide context value
    <ThemeContext.Provider value="dark">
      <ChildComponent />
    </ThemeContext.Provider>
  );
}

export default App;

* Output: Current Theme: dark


Summary
Feature useContext
Purpose Access global state without prop drilling
Works with React Context API
Alternative to Prop drilling, Redux (for simple cases)
Best for Theme, Auth, Global Settings
Not ideal for Frequently changing state (use useState or useReducer instead)