Using Redux in React
Recently, I’ve been developing a project A, with a frontend tech stack of React+Redux. Since my React foundation was weak before (only touched a small demo), and Redux was a completely new thing, I inevitably felt constrained during development and encountered many problems. After checking official docs, searching for materials, plus actual development, I’ve gained a basic understanding, so I’m recording it here.
For Redux, those who know it say it’s simple, those who don’t say it’s difficult. Is it really difficult? Not really, let me ramble about it.
Before talking about using Redux in React, let’s chat about a few questions. Understanding these will be very beneficial for using Redux.
Why do Single Page Applications (SPA) exist?
You should know that Redux is actually born to solve state management in SPAs, so we need to think about why SPAs came into being. You know, when we used to play with jQuery, we didn’t notice needing anything like Redux, right? We can’t just use Redux because others use Redux, or use React because others use React. If it’s unnecessary from the start, why make trouble for ourselves?
Recommended reading: 《The Fundamental Reason Why Modern JS Frameworks Exist》, which provides perspectives and summaries.
Modern frontend frameworks mainly solve the problem of UI and state synchronization
- Modern JS frameworks mainly solve the problem of UI and state synchronization.
- Using only native JS makes it difficult to write complex, efficient, and easily maintainable UI code.
- Web components don’t solve this main problem.
- Although it’s easy to create a framework that solves this problem using virtual DOM libraries, it’s not recommended that you actually do this!
What Problems Does Redux Solve for SPAs?
SPAs make frontend development more systematic, but also bring the problem of state management. Redux emerged to address this. The Redux official website provides a brief explanation
As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally created data that has not yet been persisted to the server. UI state is also increasing in complexity, as we need to manage active routes, selected tabs, spinners, pagination controls, and so on.
Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it’s hard to reproduce bugs or add new features.
React与Redux区别
上概念【摘自官网】
React
A JavaScript library for building user interfaces
Redux
Redux is a predictable state container for JavaScript apps
react-redux
From the above concepts, you can see that the two libraries are actually unrelated - they solve problems at different levels. In our development, because we encounter both problems simultaneously, there exists a scenario where both are used together - React frontend projects need Redux for complex state management.
When using Redux in React, this library is generally used, which you can understand as the React version of Redux
Using Redux in React
OK, now that we understand the big picture and the positioning goals of each technology, we can start learning.
For basic Redux learning, I recommend checking the official website and remember to chew on it repeatedly.
引入Redux
npm i redux --save-dev
npm i react-redux --save-dev
创建Action,Reducer,Store
Action
Reducer
Store
dispatch
具体代码直接看这里
Relationship Between the Three
If you don’t understand the three pillars of Redux, look at the diagram below
Let’s break this down:
- Components call Action execution, i.e., store.dispatch()
- When an Action initiates an operation, it needs to provide a new reducer, so calculation is needed, and the calculation process is the reducer
- Whose concept is store? It belongs to Redux. React originally didn’t have this. In the React world, a component essentially has two things: state and props. State is the component’s current state, props are parameters passed from parent to child components. Redux’s store ultimately gets reflected in the component’s props for calling. The connect function’s role is to connect the store to the target component
Using Helper Functions
In addition to the redux library itself, it’s recommended to add helper utility libraries to standardize and optimize the development experience.
redux-actions-helper
我的项目中使用了这个类库,利用辅助函数来对action 这块操作
export const initSettingAction = createAction(
SettingActionTypes.UPDATE_SETTING,
(inherit: ISetting, base: ISetting) => ({
inherit,
base
})
);
const updateSettingReducer = (state: ISettingState, action: IAction<{ inherit: ISetting; base: ISetting }>) => ({
...state,
...action.payload
});
Benefits are as follows:
- Using functions enforces that parameters in actions are at a different level than type, which strictly adheres to the standard initially set by Flux - all parameters are under the payload node, with payload and type at the same level.
- IAction type definition ensures type safety in the action area
Redux Toolkit
The official team has now released a toolkit, which new projects can consider.
Final Thoughts
By now, you should have a basic understanding. This article doesn’t have much depth - it’s mostly basics. After all, internal skills are what matter most. Once you understand the why, the rest is just a matter of practice.