13. Create Context - florypaul/ReactJS GitHub Wiki

We create context to share state and functions common across all the components. https://github.com/academind/react-complete-guide-code/tree/11-practice-food-order-app Step 1: Create Context

  1. Create a store folder adjacent to components folder
  2. Create a JS file in the store folder (name can be smaller case as it's not a component which will be used directly example cart-context.js
  3. In the JS file - create context and give the variables/states and functions which will be used across with it's initial value import React from 'react';

const CartContext = React.createContext({ items:[], totalAmount:0, addItemFunc: () => {}, removeItemFunc: (id) => {} }) export default CartContext;

Step 2: Manage Context/Create Provider (in some component with useState and useReducer. Here all the data will be managed and shared.

  1. Create a component in store folder, example CartProvider.js.
  2. In CardProvider import CartContext
  3. User Provider of CartContext
  4. give props.children in it
  5. Then add all the logic in this one component

import CartContext from './cart-content';

const CartProvider = props => { return (

    `<CartContext.Provider>`
        `{props.children}`
    `</CartContext.Provider>`
`);`

}

export default CartProvider;

Step 3 - Create and object with values and Pass to Provider as value

  1. creating object

addCartHandler()=>{} removeCartHandler()=>{} { items:[], totalAmount:0, addItemFunc:addCartHandler, removeItemFunc: removeCartHandler }

  1. Pass object as value to Provider

<CartContext.Provider value={cartContext>

Step 4: Use Provider Component - Wrap

  1. Wrap Provider to the main component which has all components example App.js

In App.js give all other components here

**Don't forget to import Provider from store folder

Step 5 - Use in individual components

  1. Import useContext in the component import { useContext } from 'react';

  2. Import CardContext itself from cart-context.js

  3. Store CartContext in a constant const cartCtx = userContext(CartContent)

  4. now we use cartCtx. instead of props.

Step 6 - Use useReducer to maintain state in CardProvider function