Plain Redux vs. Redux Toolkit - Code comparison
Comparison redux and redux-toolkit patterns with code examples
The official Redux template for Create React App includes @reduxjs/toolkit
from the get go
npx create-react-app my-app --template redux
createReducer
createAction
createSlice
createSelector
Store
import { createStore } from 'redux'
const reducer = (state, action) => {
return state
}
const store = createStore(reducer)
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root'),
)
with Redux Toolkit
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
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
}
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
// when using action constants
const counterReducer = createReducer(0, {
increment: (state, action) => state + action.payload,
decrement: (state, action) => state - action.payload,
})
// 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,
})