Menu

useReducer Hook for Cart Logic

useReducer Hook for Cart Logic

useReducer manages state through a reducer function that decides how to update it based on a dispatched action, which works better than useState when you need to handle several related actions together. The cartReducer in FalCon Store handles five action types in one place: ADD, INC, DEC, REMOVE, and CLEAR.

  • ADD checks whether a product ID already exists in the cart array and adds it only if it doesn't, which powers the already-in-cart check when someone clicks add to cart twice.
  • INC and DEC map through the array and adjust the qty for the matching id; DEC also filters out any item whose qty drops to zero, removing it from the cart automatically.
  • Every part of the app that touches the cart, like the product card or the cart page, only dispatches actions such as dispatch({ type: "ADD", id }); they never modify the cart array directly, which keeps all the cart logic centralized inside one function instead of scattered across components.

(FalCon Store) A Modern React-Based E-Commerce App UI with Admin Dashboard

AP

Abhishek Pati





Get in Touch For Details