View Code? Open in Web Editor
NEW
๐ 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! ๐ปโจ
Home Page: https://sofiane-abou-abderrahim.github.io/react-elegant-context/
HTML 2.76%
JavaScript 67.23%
CSS 30.01%
react-elegant-context's Introduction
Advanced State Management
Beyond Basic Apps & "Lifting Up State"
The Problem of Shared State: Prop Drilling
Embracing Component Composition
Sharing State with Context
Managing Complex State with Reducers
0. Understanding Prop Drilling & Project Overview
run npm install
run npm run dev
create README.md
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>
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
react-elegant-context's People
Contributors
Watchers