React Context Multiple contexts

In a React application, you may need to use multiple context objects to share data between different components. React provides a simple way to create and consume multiple context objects using context providers and consumers.

Here’s an example of how to create and consume multiple context objects:

jsx
import React, { createContext, useContext } from "react";

// Create two context objects
const ThemeContext = createContext("light");
const UserContext = createContext("guest");

function Header() {
  // Consume the context objects
  const theme = useContext(ThemeContext);
  const user = useContext(UserContext);

  return (
    

Welcome {user}!

); } function Content() { // Consume the context objects const theme = useContext(ThemeContext); const user = useContext(UserContext); return (

Here's some content for {user}.

); } function App() { return ( // Provide the context objects to child components
); }

In this example, we’re creating two context objects (`ThemeContext` and `UserContext`) using the `createContext` function. We’re also defining two child components (`Header` and `Content`) that consume both context objects using the `useContext` hook.

We’re using the `ThemeContext.Provider` and `UserContext.Provider` components to provide the context objects to child components. We’re also setting the value of each context object using the `value` prop.

In the `Header` and `Content` components, we’re using the `useContext` hook to consume both context objects. The `useContext` hook returns the current value of the context objects, which we can use to render components based on the current theme and user.

By using multiple context objects, we can share data between different components without having to pass props down through every level of the component tree. We can also create reusable components that can be used in different parts of our application, and provide a consistent user experience across different devices and platforms.

Overall, React Context provides a powerful and flexible way to create and consume multiple context objects in your React application. By using context providers and consumers, you can share data between components, create reusable components, and provide a consistent user experience.