Redux Toolkit and State Management
React¹⁷.0.2, react-redux⁷.2.4, @reduxjs/toolkit¹.6.0, Created at July 21, 2021, Read Series…
@reduxjs/toolkit, react-redux, and redux
Redux is a predictable state container for JavaScript apps.
React Redux is the official React UI bindings layer for Redux. It lets your React components read data from a Redux store, and dispatch actions to the store to update state.
Redux Toolkit, an officially recommended and a SOPE library that stands for Simple, Opinionated, Powerful, and Effective state management library. It allows us to write more efficient code, speed up the development process, and automatically apply the best-recommended practices. It was mainly created to solve the THREE MAJOR ISSUES with Redux:
— Configuring a Redux store is too complicated
— Have to add a lot of packages to build a large scale application
— Redux requires too much boilerplate code which makes it cumbersome to write efficient and clean code.
npm install @reduxjs/toolkit react-redux
src/layout/appSlice.ts
[Try to understand] Define appSlice with increment, decrment, incrementByAmount actions.
import { createSlice } from '@reduxjs/toolkit';const appSlice = createSlice({
name: 'app',
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer
// library, which detects changes to a "draft state" and produces a
// brand new immutable state based off those changes
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
},
}
});export const { increment, decrement, incrementByAmount } = appSlice.actions
export default appSlice.reducer;
src/store/CombinedReducers.ts
[Try to understand] Import appSlice into combineReducers, then export reducers. Then get type of reducers as RootState. RootState is going to be reference when useSelector(state: RootState)
import { combineReducers } from "@reduxjs/toolkit";import app from "src/layout/appSlice";export const reducers = combineReducers({
app: app
});export type RootState = ReturnType<typeof reducers>
src/store/Store.ts
[Try to understand] reducers in CombinedReducers.ts is imported.
@reduxjs/toolkit configureStore: A friendly abstraction over the standard Redux
createStore
function that adds good defaults to the store setup for a better development experience. Please search configureStore v.s.createStore
for more information.
import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit';import { reducers } from './CombinedReducers';const store = configureStore({
reducer: reducers
// TODO: the following commented out code can suppress: "A non-
// serializable value was detected in the state, in the path:"
,
middleware: getDefaultMiddleware({
serializableCheck: {
ignoredActions: ['persist/PERSIST'],
// // Ignore these field paths in all actions
// ignoredActionPaths: ['app.alert.buttons[0].handler'],
// // Ignore these paths in the state
// ignoredPaths: ['items.dates']
// persist/PERSIST is from
// 'redux-persist/integration/react'
}
})
})export default store;
Usage in src/App.tsx
[Try to understand] useSelector: extract data from the Redux store state(RootState) to local variables/state to shorten the reference path.
[Try to understand] useDispatch: fire actions(increment), with/without parameters, into your reducers.
import { useDispatch, useSelector } from 'react-redux';
import { increment } from './layout/appSlice';
import { RootState } from './store/CombinedReducers';export default function App() {
const count = useSelector((state: RootState) => state.app.value);
const dispatch = useDispatch();return (
{/* Basic-1.4. react-redux */}
<Accordion>
<AccordionSummary expandIcon={<ExpandMore />} aria-controls="panel2a-content" id="panel2a-header-basic-1.2">
<Typography>Basic-1.4. react-redux {count}</Typography>
</AccordionSummary>
<AccordionDetails>
<Button color="inherit" aria-label="Increment value"
onClick={() => dispatch(increment())}>Increment</Button>
</AccordionDetails>
</Accordion>
);
}
Github commits is here: Basic-1.4. react-redux
Conclusion
Redux Toolkit is a great option to use when getting started with Redux. It simplifies the code and helps to manage the Redux state by reducing the boilerplate code.