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 File

    MyContext.js

    
                  import 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 (
                      <MyContext.Provider value={{ value, updateValue }}>
                        {children}
                      </MyContext.Provider>
                    );
                  };
    
    
                  
    3. Wrap Your App with the Provider

    App.js

    
                    import React from "react";
                    import { MyProvider } from "./MyContext";
                    import MyComponent from "./MyComponent";
    
                    function App() {
                      return (
                        <MyProvider>
                          <MyComponent />
                        </MyProvider>
                      );
                    }
    
                    export default App;
    
    
                    
    4. Use Context in Any Component

    MyComponent.js

    
                      import React, { useContext } from "react";
                      import { MyContext } from "./MyContext";
    
                      const MyComponent = () => {
                        const { value, updateValue } = useContext(MyContext);
    
                        return (
                          <div>
                            <p>Context Value: {value}</p>
                            <button onClick={() => updateValue("Updated from Component")}>
                              Update Context
                            </button>
                          </div>
                        );
                      };
    
                      export default MyComponent;
    
    
                      

    3. Common Use Cases

    1. Cart state (addToCart, removeFromCart)

    2. Auth state (login, logout)