Accidental state mutation
In the reducer function we can mistakenly mutate the state, which causes a lot bugs and these bugs are hard to debug. See how we can mutate the state in redux. Redux Toolkit works differently to handle this problem, Redux Toolkit uses Immer library to mutate the state. Where syntax looks like we are mutating the state but these are just immutable updates. Immer library internally mutates the state.
// Redux code without Redux Toolkit
function todosReducer(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
state.todos.push(action.payload); // Mutating state
return state;
default:
return state;
}
}
// Redux Toolkit code
import { createSlice } from '@reduxjs/toolkit';
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: (state, action) => {
// Using Immer library to avoid mutation
state.push(action.payload);
},
},
});
Why was Redux Toolkit created?
Redux Toolkit was created to improve the overall development experience and to simplify the setup of the redux store and state management tasks. Redux Toolkit is also known as RTK in short. In this article, we’ll discuss the problems that developers face while using Redux and how Redux Toolkit comes up with the solution.
Table of Content
- Too much Boilerplate Code
- Accidental state mutation
- Typescript Support
- Asynchronous Tasks