DEV Community

Cover image for React Hooks Snippet: Shopping Cart
Ryan Kahn (he/him)
Ryan Kahn (he/him)

Posted on • Updated on

React Hooks Snippet: Shopping Cart

Hey all! How would you model a shopping cart with React Hooks? Here's how I would do it!

The main things to look at:

  • This is written in Typescript, to assist the gist also contains the same code in JavaScript.
  • The Types!
    • An order is Tuple of an ID (which is a string) and a Quantity (which is a number).
    • The Cart is a Record, which is an object where the keys are the item IDs and the values are their Quantity.
  • The reducer for useReducer doesn't take a Flux Standard Action! 🤯😱 Let's keep things less complex! Here our reducer is just taking our Order tuples, and reducing the Cart from that.
  • We have two effects we run in our useShoppingCart hook.
    • First, we fetch the saved cart from the server, and add all those items to the cart
    • Second, every time the cart updates we POST that to the server. We keep track of the saved and error status with useState.
    • Could we save the cart before we fetch the cart? I dunno! Maybe?

If shopping carts aren't your thing, but you like this style, leave a comment with what hooks snippet I should write next!

Top comments (0)