Understanding the useReducer Hook
You probably have some experience using Redux (react-redux
) with class components, and if that is the case, then you will understand how useReducer
works. The concepts are basically the same: actions, reducers, dispatch, store, and state. Even if, in general, it seems very similar to react-redux, they have some differences. The main difference is that react-redux provides middleware and wrappers such as thunk, sagas, and many more besides, while useReducer
just gives you a dispatch
method that you can use to dispatch plain objects as actions. Also, useReducer
does not have a store by default; instead, you can create one using useContext
, but this is just reinventing the wheel.
Let’s create a basic application to understand how useReducer
works. You can start by creating a new React app:
npx create-vite reducer --template react-ts
Then, as always, you can delete all files in your src
folder except App.tsx
and index.tsx
to start...