Typescript Support
Redux does not provide proper Typescript Support, thus we need to write a lot of type definitions for our code which ultimately results in large boilerplate code and poor code maintenance. Redux toolkit comes with built-in type definitions which means we don’t have to manually write a lot of type definitions which in turn saves a lot of time and code.
// Redux code without Redux Toolkit
interface Todo {
id: number;
text: string;
completed: boolean;
}
interface AddTodoAction {
type: 'ADD_TODO';
payload: Todo;
}
interface RemoveTodoAction {
type: 'REMOVE_TODO';
payload: { id: number };
}
type TodoActionTypes = AddTodoAction | RemoveTodoAction;
function todosReducer(
state: Todo[] = [], action: TodoActionTypes): Todo[] {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload];
case 'REMOVE_TODO':
return state.filter(
todo => todo.id !== action.payload.id);
default:
return state;
}
}
// Redux Toolkit code
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
interface Todo {
id: number;
text: string;
completed: boolean;
}
const todosSlice = createSlice({
name: 'todos',
initialState: [] as Todo[],
reducers: {
addTodo: (state, action: PayloadAction<Todo>) => {
state.push(action.payload);
},
removeTodo: (
state, action: PayloadAction<{ id: number }>) => {
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