Skip to main content
InterviewHubPRO
Section Overview
Q282

Question 282 of 407

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

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

Can You Use Multiple Contexts in One Component?

mid LevelCode ExampleComponentsHooks

Yes, it is possible. You can use multiple contexts inside the same component by calling useContext multiple times, once for each context.

It can be achieved with below steps,

  • Create multiple contexts using createContext().
  • Wrap your component tree with multiple <Provider>s.
  • Call useContext() separately for each context in the same component.

Example: Using ThemeContext and UserContext Together

js
import React, { createContext, useContext } from 'react';

// Step 1: Create two contexts
const ThemeContext = createContext();
const UserContext = createContext();

function Dashboard() {
 // Step 2: Use both contexts
 const theme = useContext(ThemeContext);
 const user = useContext(UserContext);

 return (
   <div style={{ background: theme === 'dark' ? '#333' : '#fff' }}>
     <h1>Welcome, {user.name}</h1>
     <p>Current theme: {theme}</p>
   </div>
 );
}

// Step 3: Provide both contexts
function App() {
 return (
   <ThemeContext.Provider value="dark">
     <UserContext.Provider value={{ name: 'Alex' }}>
       <Dashboard />
     </UserContext.Provider>
   </ThemeContext.Provider>
 );
}

export default App;