useContext
ParentApp
Header
Section
Title1
Setting Global Context from Title 1
abc@gmail.com
Main
Section
Title 2
Arjunan coming from Context
abc@gmail.com coming from Context
import { useState, createContext } from "react";
export const Context = createContext();
const ContextProvider = ({ children }) => {
const [name, setName] = useState("Arjunan coming from Context");
const ContextValue = { name, setName, email: "abc@gmail.com" };
return <Context.Provider value={ContextValue}>{children}</Context.Provider>;
};
export default ContextProvider;
import { useContext } from "react";
import { Context } from "./ContextProvider";
const Component = () => {
const ContextValue = useContext(Context);
function changeName() {
ContextValue.setName((prev) => "Appu set from Title 1");
}
return (
<>
<p>{ContextValue.email}</p>
<button onClick={changeName}>Change Name</button>
</>
);
};