You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
1. Prop Drilling: Component Composition as a Solution
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 in App.jsx
2. Creating & Providing The Context
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>
3. Consuming the Context
consume the CartContext in the Cart.jsx component
import { CartContext }
import { useContext }
set useContext(CartContext) as a value to cartCtx
use cartCtx to access the items property
add a value to <CartContext.Provider> in App.jsx
destructure CartContext so that you use { items } straight away
4. Linking the Context to State
set the value of <CartContext.Provider> to the shoppingCart state in App.jsx to link the context to state
to edit the state with context, create a ctxValue const which will be an object
use CartContext in Product.jsx
add addItemToCart function as an initial value in shopping-cart-context.jsx file
5. A Different Way Of Consuming Context
use the <CartContext.Consumer> component to wrap the JSX code in Cart.jsx
pass a function as a child inside <CartContext.Consumer> to automatically receive the consumed cartCtx value as a parameter
6. Migrating the Entire Demo Project to use the Context API
remove extra props
use CartContext in Header.jsx
add the updateItemQuantity function in the ctxValue constant in App.jsx & in shopping-cart-context.jsx
extract updateItemQuantity in Cart.jsx & call it on the buttons
7. Outsourcing Context & State Into a Separate Provider Component
export a CartContextProvider function in shopping-cart-context.jsx
import CartContextProvider & use it in App.jsx
8. Introducing the useReducer Hook
import useReducer in shopping-cart-context.jsx
use useReducer() hook to manage the state
9. Dispatching Actions & Editing State with useReducer
dispatch actions with useReducer() hook in shopping-cart-context.jsx
edit the shoppingCartReducer function with the actions values
About
π Elevate your React apps with advanced state management techniques! Explore component composition, Context API for seamless state sharing, and Reducers for managing complex states. Check out "React Elegant Context" demo now! π»β¨