- The Problem of Shared State: Prop Drilling
- Embracing Component Composition
- Sharing State with Context
- Managing Complex State with Reducers
- run
npm install
- run
npm run dev
- create
README.md
- embrace component composition by refactoring the
Shop.jsx
component to a wrapper around the list of products - output the
<Product />
component inside the<Shop>
component inApp.jsx
- create a
store
folder - create a
shopping-cart-context.jsx
file - inside of this file, create a
CartContext
context - provide it to this application and wrap it around the components in
App.jsx
by using<CartContext.Provider>
- consume the
CartContext
in theCart.jsx
component- import
{ CartContext }
- import
{ useContext }
- set
useContext(CartContext)
as a value tocartCtx
- use
cartCtx
to access theitems
property
- import
- add a value to
<CartContext.Provider>
inApp.jsx
- destructure
CartContext
so that you use{ items }
straight away
- set the value of
<CartContext.Provider>
to theshoppingCart
state inApp.jsx
to link the context to state - to edit the state with context, create a
ctxValue
const which will be an object - use
CartContext
inProduct.jsx
- add
addItemToCart
function as an initial value inshopping-cart-context.jsx
file
- use the
<CartContext.Consumer>
component to wrap the JSX code inCart.jsx
- pass a function as a child inside
<CartContext.Consumer>
to automatically receive the consumedcartCtx
value as a parameter
- remove extra props
- use
CartContext
inHeader.jsx
- add the
updateItemQuantity
function in thectxValue
constant inApp.jsx
& inshopping-cart-context.jsx
- extract
updateItemQuantity
inCart.jsx
& call it on the buttons
- export a
CartContextProvider
function inshopping-cart-context.jsx
- import
CartContextProvider
& use it inApp.jsx
- import
useReducer
inshopping-cart-context.jsx
- use
useReducer()
hook to manage the state
- dispatch actions with
useReducer()
hook inshopping-cart-context.jsx
- edit the
shoppingCartReducer
function with the actions values