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
- Create a store folder adjacent to components folder
- 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
- 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.
- Create a component in store folder, example CartProvider.js.
- In CardProvider import CartContext
- User Provider of CartContext
- give props.children in it
- 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
- creating object
addCartHandler()=>{}
removeCartHandler()=>{}
{
items:[],
totalAmount:0,
addItemFunc:addCartHandler,
removeItemFunc: removeCartHandler
}
- Pass object as value to Provider
<CartContext.Provider value={cartContext>
Step 4: Use Provider Component - Wrap
- 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
-
Import useContext in the component import { useContext } from 'react';
-
Import CardContext itself from cart-context.js
-
Store CartContext in a constant const cartCtx = userContext(CartContent)
-
now we use cartCtx. instead of props.
Step 6 - Use useReducer to maintain state in CardProvider function