Redux evolution with Redux Toolkit (RTK)
Redux is a state container for JS applications. It is widely used for state management in SPA but we must have read in every blog and documentation that the downside to Redux is that there’s a lot of initial boilerplate.
But now with Redux Toolkit everything seems to be smooth, quick, and easy.
Before moving into the RTK library let’s dive into some core concepts of redux.
There are 4 pillars of Redux
- Actions – object containing the type of action and payload, they trigger an event.
- Middlewares – point between dispatching an action and the action request reaching the reducer, generally used for logging and fetching data from API.
- Immutable Store – redux store is immutable it means whenever we want to update any value in store we need to create a new object of the current state with the updated key-value and reference of that object should be different.
Accidentally mutating state in reducers is the most common mistake developers make.
With Redux Toolkit store configuration becomes swift and easy, middlewares are predefined based on environment.
Superpowers of Redux Toolkit !
- No need to get crazy about naming different type constants for each action which becomes a headache in large applications.
- No switch case statement in reducers makes code compact and readable.
- No need to be concerned about immutability, RTK library handles on its own.
- All the logic goes into a single file which we call slices.
- We pass these slices into root reducers.
CreateSlice automatically creates action creators and action types that correspond to reducers and states. Each slice denotes a particular slice of the state tree. It takes an object as an argument, where the name denotes the name of the slice or the key of the state. A reducer is an object with methods where each method handles a specific action type. Reducer functions have 2 arguments, the first one is the current state and a second argument is an object containing action type and payload.
It returns us an object with actions and reducers.
Redux Toolkit + React App Boilerplate
This project is build on following versions –
Node – v14.18.0
React – v17
@Redux/Toolkit – v1.6