[React] Use the React Context API to Globally Manage State

Using React hooks like useState makes it easy to manage things like a shopping cart, but that state may only be available one instance at a time. What if we wanted that state to be available between multiple pages?

We can take advantage of React's Context API which lets us extend our cart state by making that state available anywhere we want in the app.

In our app, we want to move the cart from the Home page component to the header which requires us to use context. We will wrap our app in a CartContext.Provider and pass in cart from our cart hook. This will allow us to grab subtotal and checkout for the Nav component.

 

If there is one state which both used in pageA and pageB, we can lift this state into Context, then it is availabel for both pageA & B

 

A hook file, contains both Context and state.

复制代码
import { useState, useContext, createContext } from 'react';
import { initiateCheckout } from '../lib/payments.js'
import products from '../products.json';

const defaultCart = {
  products: {}
}

export const CartContext = createContext();

export function useCartState() {

  const [cart, updateCart] = useState(defaultCart);

  ...return {
    cart,
    subtotal,
    quantity,
    addToCart,
    checkout
  }

}
export function useCart() {
  const cart = useContext(CartContext);
  return cart;
}
复制代码

 

index.js:

复制代码
function MyApp({ Component, pageProps }) {
  const cart = useCartState();
  return (
    <CartContext.Provider value={cart}>
      <Nav />
      <Component {...pageProps} />
    </CartContext.Provider>
  )
}
复制代码

 

Uage:

复制代码
const Nav = () => {
  
    const { subtotal, checkout} = useCart();

  return (
    <nav className={styles.nav}>
      <p className={styles.navTitle}>
        Space Jelly Shop
      </p>
      <p className={styles.navCart}>
        <button onClick={checkout}>
          <FaShoppingCart /> ${subtotal}
        </button>
      </p>
    </nav>
  )
}

export default Nav;
复制代码

 

posted @   Zhentiw  阅读(99)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-02-01 [Functional Programming ADT] Adapt Redux Actions/Reducers for Use with the State ADT
2018-02-01 [MST] Create Dynamic Types and use Type Composition to Extract Common Functionality
2017-02-01 [TypeScript] Use the never type to avoid code with dead ends using TypeScript
2016-02-01 [Regex Expression] Use Shorthand to Find Common Sets of Characters
2016-02-01 [Regex Expression] Find Sets of Characters
2016-02-01 [Regular Expressions] Find Repeated Patterns
2016-02-01 [Regular Expressions] Find Plain Text Patterns
点击右上角即可分享
微信分享提示