React Context Creating and consuming context

React Context is a powerful feature that allows you to share data between components without having to pass props down through every level of the component tree. Instead, you can define a “context” object that can be consumed by any component that needs it.

Here’s an example of how to create and consume a React Context:

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

// Create a context object
const ThemeContext = createContext("light");

function Header() {
  // Consume the context object
  const theme = useContext(ThemeContext);

  return (
    

My App

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

Welcome to my app!

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

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

We’re using the `ThemeContext.Provider` component to provide the `ThemeContext` object to child components. The `Provider` component takes a `value` prop that specifies the value of the context object.

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

By using React Context, we can share data between 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 share data between components in your application. By using React Context, you can create reusable components, provide a consistent user experience, and share data between components without having to pass props down through every level of the component tree.