Skip to main content
InterviewHubPRO
Section Overview
Q264

Question 264 of 407

Part 9: React Hooks Deep Dive (262 - 316)

65%
React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)

What is useContext? What are the steps to follow for useContext?

junior LevelCode ExampleHooks

The useContext hook is a built-in React Hook that lets you access the value of a context inside a functional component without needing to wrap it in a <Context.Consumer> component.

It helps you avoid prop drilling (passing props through multiple levels) by allowing components to access shared data like themes, authentication status, or user preferences.

The usage of useContext involves three main steps:

Step 1 : Create the Context

Use React.createContext() to create a context object.

jsx
 import React, { createContext } from 'react'; 

 const ThemeContext = createContext(); // default value optional

You typically export this so other components can import it.

Step 2: Provide the Context Value

Wrap your component tree (or a part of it) with the Context.Provider and pass a value prop.

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

Now any component inside <ThemeContext.Provider> can access the context value.

Step 3: Consume the Context with **useContext**

In any functional component inside the Provider, use the useContext hook:

jsx
 import { useContext } from 'react'; 
 function MyComponent() {
     const theme = useContext(ThemeContext); // theme = "dark"
     return <p>Current Theme: {theme}</p>; 
 }