Drife Code blogs and ai

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

Cover Image for We will tell you how to create a global context in React app , node v20
senior developer gautam swami
Gautam swami

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>
);


More Stories

Cover Image for How I Created a Mobile App Portfolio with AI in Just One Hour

How I Created a Mobile App Portfolio with AI in Just One Hour

Discover how I created a professional mobile app portfolio for a client in just one hour using Vercel's v0 AI. From generating the base code with a simple prompt to customizing it and deploying it on Vercel, this blog details the step-by-step process—highlighting the power of AI in modern web development. And yes, even this blog was crafted with a little help from AI! 🚀

senior developer gautam swami
Gautam swami
Cover Image for Using wireless debugging for Device connection and how to connect android device over wifi for development

Using wireless debugging for Device connection and how to connect android device over wifi for development

Using wireless debugging for Device connection and how to connect android device over wifi for development

senior developer gautam swami
Gautam swami