FrontendDeveloper.in

React question detail

Can You Use Multiple Contexts in One Component?

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

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 (
<h1>Welcome, {user.name}</h1>
);
 }

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

 export default App;
Back to all React questions
Get LinkedIn Premium at Rs 399