React Hooks: React Context Api Hook
Copy Below Code
View As A Text File
Show Text Only
Show API
Edit Code
Context api use is same Redux.
Steps:
1- In your index.js / main.js / app.js Create a Context and Wrap all childrens in a Provider. That provider will take, Context value
2- We will access context using "useContext(appContext)", it will take our context name
index.js:
export const AppContext = createContext(); // this exported context will use all over the way
const ContextApi = () => {
const [state, setState] = useState({
variant: "labs",
app: "reactflow",
counter: 0,
});
return (
<AppContext.Provider value={{ state, setState }}> // We will define a provider here and provide our values to it.
<ComponentA />
</AppContext.Provider>
);
};
export default ContextApi;
componentA.js:
import { useContext } from "react";
import { AppContext } from ".";
import ComponentC from "./component-3";
const ComponentA = () => {
const { state } = useContext(AppContext); // we will pass our root defined Context name
return (
<div>
<h1>Component A: From Index Value - "{state.variant}"</h1>
<h1>Component A: {state.counter}</h1>
<ComponentB />
</div>
);
};
export default ComponentA;
componentB.js:
import { useContext } from "react";
import { AppContext } from ".";
const ComponentC = () => {
const { setState } = useContext(AppContext);
const handleClick = (e) => {
setState((st) => ({ ...st, counter: st.counter + 1 }));
};
return (
<div>
<h1>Component C</h1>
<button onClick={handleClick}>Click on Component-C to Add Counter</button>
</div>
);
};
export default ComponentC;