Plain Redux vs. Redux Toolkit - Code comparison
August 1, 2020
The official Redux template for Create React App includes @reduxjs/toolkit from the get go
code
npx create-react-app my-app --template redux
createReducercreateActioncreateSlicecreateSelector
Store
code
import { createStore } from "redux";
const reducer = (state, action) => {
return state;
};
const store = createStore(reducer);
code
import { Provider } from "react-redux";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root"),
);
with Redux Toolkit
code
import { configureStore } from "@reduxjs/toolkit";
import rootReducer from "./reducers";
const store = configureStore({ reducer: rootReducer });
// The store now has redux-thunk added and the Redux DevTools Extension is turned on
Reducers
Plain redux
code
const initialState = { value: 0 };
function counterReducer(state = initialState, action) {
// Check to see if the reducer cares about this action
if (action.type === "counter/increment") {
// If so, make a copy of `state`
return {
...state,
// and update the copy with the new value
value: state.value + 1,
};
}
// otherwise return the existing state unchanged
return state;
}
code
function counterReducer(state = 0, action) {
switch (action.type) {
case "increment":
return state + action.payload;
case "decrement":
return state - action.payload;
default:
return state;
}
}
Redux toolkit
code
// when using action constants
const counterReducer = createReducer(0, {
increment: (state, action) => state + action.payload,
decrement: (state, action) => state - action.payload,
});
code
// when using actions generated by createAction()
const increment = createAction("increment");
const decrement = createAction("decrement");
const counterReducer = createReducer(0, {
// actions used directly as the keys here, using computed property syntax
[increment]: (state, action) => state + action.payload,
[decrement.type]: (state, action) => state - action.payload,
});