Now that we have our React version of our application all ready to go, it's time to start thinking about how to use a state manager in the App Router.
Redux is the OG state manager, and follows a simple, three-part model:
First, there's a Store that holds your data. Then there are Selectors which you can use in your components to get access to the data in that store. Finally, there are Actions that are dispatched to the Redux store. These actions are then handled by reducers that mutate the data in the store.
Redux has a nice unidirectional flow: Actions go into the store, and trigger mutations. The mutations essentially trigger the selectors, which then update the display of the data on the page.
In a traditional Redux setup, there is only a single store. That single store is just declared as a global variable, often in a store.ts
file.
However, that's not going to work in our case because "Rule Number One" says no global variables!
Challenge
In this challenge, you'll be implementing a Redux store using context instead of relying on a global variable.
Starting with the 03-cart-context-with-initial-state
example we just finished, you'll need to remove the existing CartContext
object and replace it with a Redux store.
You'll need to install redux
, react-redux
and @reduxjs/toolkit
.
You'll need to remove the existing CartContext
object and replace it with a Redux store.
Remember, you cannot safely use a Redux store that is defined as a global store.
Redux Example
Here is an example of a count
slice created with Redux Toolkit:
Here is an example createStore
function that creates a new Redux store.
Here is a way to export the setCount
action, as well as handy types and a selector for the count
:
To dispatch actions to the store use useDispatch
to get a dispatch
function. You use it like this:
Give it a try, and we'll walk through it together in the next video!