React Js / Components / Data sharing between components - using Context
Data sharing using context
-
1. Step
context is used to access and update the state (data) from any component 1. Steps
1. Create context file (createContext)
2. Define provider and share value + functions
3. Wrap your app with provider (
) 4. Use useContext(MyContext) in any component
5. Call state/functions from context (e.g., onClick)
2. Examples
1. Create a Context FileMyContext.js
3. Wrap Your App with the Providerimport React, { createContext, useState } from "react"; // 1. Create context export const MyContext = createContext(); // 2. Create provider component export const MyProvider = ({ children }) => { const [value, setValue] = useState("Hello from Context!"); const updateValue = (newValue) => setValue(newValue); return ( {children} ); };App.js
4. Use Context in Any Componentimport React from "react"; import { MyProvider } from "./MyContext"; import MyComponent from "./MyComponent"; function App() { return ( ); } export default App;MyComponent.js
import React, { useContext } from "react"; import { MyContext } from "./MyContext"; const MyComponent = () => { const { value, updateValue } = useContext(MyContext); return ( ); }; export default MyComponent;Context Value: {value}
3. Common Use Cases
1. Cart state (addToCart, removeFromCart)
2. Auth state (login, logout)
MANVIA BLOG