Migrating to Redux Toolkit
Demonstrate the refactoring process of a traditional Redux implementation to Redux Toolkit, leveraging its conventions and utilities to simplify setup and usage.
import { createStore, combineReducers } from 'redux';
// Example of traditional Redux reducer
function todosReducer(state = [], action) {
switch(action.type) {
case 'ADD_TODO':
return [...state, action.payload];
default:
return state;
}
}
// Combine reducers
const rootReducer = combineReducers({
todos: todosReducer
});
// Create Redux store
const store = createStore(rootReducer);
Traditional Redux setup where we import createStore and combineReducers from redux. We define a todosReducer for handling 'ADD_TODO' actions and combine it into a rootReducer which is then used to create the Redux store.
import { configureStore } from '@reduxjs/toolkit';
// Example of Redux Toolkit reducer using createReducer
import { createReducer } from '@reduxjs/toolkit';
const todosReducer = createReducer([], {
'ADD_TODO': (state, action) => [...state, action.payload],
});
// Create Redux store using the Redux Toolkit
const store = configureStore({
reducer: {
todos: todosReducer
}
});
Refactoring to Redux Toolkit by importing configureStore and createReducer. We refactor the todosReducer using createReducer which simplifies the implementation. Then we use configureStore to create the Redux store, which accepts our reducers in a more straightforward object notation.
import { createAction, createSlice } from '@reduxjs/toolkit';
// Defining actions and reducers together using createSlice
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: (state, action) => {
state.push(action.payload);
},
},
});
// Generated action creator
export const { addTodo } = todosSlice.actions;
// Redux Toolkit store with a slice reducer
const store = configureStore({
reducer: {
todos: todosSlice.reducer
}
});
Using createSlice from Redux Toolkit to define the 'todos' slice, which encapsulates both initial state and reducer logic. This slice automatically generates action creators and types. We export the generated 'addTodo' action creator and use the slice reducer in the store setup with configureStore.