Notes

Plain Redux vs. Redux Toolkit - Code comparison

Comparison redux and redux-toolkit patterns with code examples

Edit on GitHub

Redux
2 minutes

The official Redux template for Create React App includes @reduxjs/toolkit from the get go

1npx create-react-app my-app --template redux
  • createReducer
  • createAction
  • createSlice
  • createSelector

Store

1import { createStore } from 'redux'
2
3const reducer = (state, action) => {
4  return state
5}
6
7const store = createStore(reducer)
1import { Provider } from 'react-redux'
2
3ReactDOM.render(
4  <Provider store={store}>
5    <App />
6  </Provider>,
7  document.getElementById('root'),
8)

with Redux Toolkit

1import { configureStore } from '@reduxjs/toolkit'
2
3import rootReducer from './reducers'
4
5const store = configureStore({ reducer: rootReducer })
6// The store now has redux-thunk added and the Redux DevTools Extension is turned on

Reducers

Plain redux

 1const initialState = { value: 0 }
 2
 3function counterReducer(state = initialState, action) {
 4  // Check to see if the reducer cares about this action
 5  if (action.type === 'counter/increment') {
 6    // If so, make a copy of `state`
 7    return {
 8      ...state,
 9      // and update the copy with the new value
10      value: state.value + 1,
11    }
12  }
13  // otherwise return the existing state unchanged
14  return state
15}
 1function counterReducer(state = 0, action) {
 2  switch (action.type) {
 3    case 'increment':
 4      return state + action.payload
 5    case 'decrement':
 6      return state - action.payload
 7    default:
 8      return state
 9  }
10}

Redux toolkit

1// when using action constants
2const counterReducer = createReducer(0, {
3  increment: (state, action) => state + action.payload,
4  decrement: (state, action) => state - action.payload,
5})
1// when using actions generated by createAction()
2const increment = createAction('increment')
3const decrement = createAction('decrement')
4
5const counterReducer = createReducer(0, {
6  // actions used directly as the keys here, using computed property syntax
7  [increment]: (state, action) => state + action.payload,
8  [decrement.type]: (state, action) => state - action.payload,
9})