Use the React Context API to Globally Manage Cart State in a Next.js App

InstructorColby Fayock

Share this video with your friends

Send Tweet

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.

NHI TRAN
~ a month ago

Is there a performance worry about using usecontext with that data that will frequently change? Doesn’t updatingcart state trigger a rerender for all items?

Colby Fayockinstructor
~ a month ago

Is there a performance worry about using usecontext with that data that will frequently change? Doesn’t updatingcart state trigger a rerender for all items?

hey! It might be a small hit but it should be negligible, especially compared to the benefits being able to manage that state globally