Too much Boilerplate Code
Redux traditionally requires writing a lot of repetitive code for managing state in applications, leading to a poor developer experience and increased chances of errors. Redux Toolkit addresses this issue by providing simpler APIs like configureStore()
and createSlice()
that reduce boilerplate code significantly. It automatically handles action types and creators, resulting in cleaner and bug-free code, and improving overall development efficiency.
// Redux code without Redux Toolkit
const ADD_TODO = 'ADD_TODO';
const REMOVE_TODO = 'REMOVE_TODO';
const initialState = {
todos: [],
};
function todosReducer(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload],
};
case REMOVE_TODO:
return {
...state,
todos: state.todos.filter(
todo => todo.id !== action.payload.id),
};
default:
return state;
}
}
// Action creators
function addTodoAction(todo) {
return { type: ADD_TODO, payload: todo };
}
function removeTodoAction(todoId) {
return { type: REMOVE_TODO, payload: { id: todoId } };
}
// Redux Toolkit code
import { createSlice } from '@reduxjs/toolkit';
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: (state, action) => {
state.push(action.payload);
},
removeTodo: (state, action) => {
return state.filter(
todo => todo.id !== action.payload.id);
},
},
});
export const { addTodo, removeTodo } = todosSlice.actions;
export default todosSlice.reducer;
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
Contact Us