We will tell you how to create a global context in React app , node v20



Firstly, create a separate file containing global values with any name-appropriate name that will add the keyword context after it.
We are using the name - themeContext.js
In this file create a basic state using useState hook
import React, { createContext, useState } from "react";
export const ThemeContext = createContext();
export default function ThemeContextProvider(props) {
const [theme, setTheme] = useState("light");
let data = {theme, setTheme}
return (
<ThemeContext.Provider value={data}>
{props?.children}
</ThemeContext.Provider>
);
}
Now, you can jump to the main file where all routes or code is being rendered in my case it is index.js
Import the ThemeContext here and use it around the rendering div like
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { ThemeContext } from "./context/themecontext";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<ThemeContext.Consumer>{() => <App />}</ThemeContext.Consumer>
</React.StrictMode>
);

