[Organization and sharing] 7 popular React state management tools
Apr 26, 2023 pm 05:47 PMRecently I am working on organizing the project technology stack;
As the team becomes larger, the number of people increases, and the number of projects increases;
The unified technology stack is A very necessary thing;
There are many React state management tools, but choosing a suitable state management tool is actually very important;
Follow me today Let me share with you some very popular React state management that I have compiled. I hope it will be helpful to you.
【 1. Mobx 】
Mobx
#MobX can run independently of React, but they usually Used together; the new version of mobx-react-lite library is very lightweight; when using it, you only need to use the exported observer package component; and then introduce the state;
import React from "react" import ReactDOM from "react-dom" import { makeAutoObservable } from "mobx" import { observer } from "mobx-react-lite" class Timer { secondsPassed = 0 constructor() { makeAutoObservable(this) } increaseTimer() { this.secondsPassed += 1 } } const myTimer = new Timer() //被`observer`包裹的函數(shù)式組件會(huì)被監(jiān)聽(tīng)在它每一次調(diào)用前發(fā)生的任何變化 const TimerView = observer(({ timer }) => <span>Seconds passed: {timer.secondsPassed} </span>) ReactDOM.render(<TimerView timer={myTimer} />, document.body)
【 2. Redux 】
Redux
Redux is also a very popular state management tool, but it is more cumbersome than other state management tools; of course I like it People who use Redux will also find Redux very elegant;
import { createStore } from 'redux' /** * This is a reducer - a function that takes a current state value and an * action object describing "what happened", and returns a new state value. * A reducer's function signature is: (state, action) => newState * * The Redux state should contain only plain JS objects, arrays, and primitives. * The root state value is usually an object. It's important that you should * not mutate the state object, but return a new object if the state changes. * * You can use any conditional logic you want in a reducer. In this example, * we use a switch statement, but it's not required. */ function counterReducer(state = { value: 0 }, action) { switch (action.type) { case 'counter/incremented': return { value: state.value + 1 } case 'counter/decremented': return { value: state.value - 1 } default: return state } } // Create a Redux store holding the state of your app. // Its API is { subscribe, dispatch, getState }. let store = createStore(counterReducer) // You can use subscribe() to update the UI in response to state changes. // Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly. // There may be additional use cases where it's helpful to subscribe as well. store.subscribe(() => console.log(store.getState())) // The only way to mutate the internal state is to dispatch an action. // The actions can be serialized, logged or stored and later replayed. store.dispatch({ type: 'counter/incremented' }) // {value: 1} store.dispatch({ type: 'counter/incremented' }) // {value: 2} store.dispatch({ type: 'counter/decremented' }) // {value: 1}
It is not easy to get started with Redux quickly, and you need to think about it carefully; but fortunately, redux officially launched the new Redux-tookit The steps for using Redux are greatly simplified.
【 3. Rematch 】
Rematch
Rematch continues the advantages of Redux, and the core concept is still based on Redux; but compared to Redux, it is simply too powerful! .
import { createModel } from "@rematch/core"; import { RootModel } from "."; export const count = createModel<RootModel>()({ state: 0, // initial state reducers: { // handle state changes with pure functions increment(state, payload: number) { return state + payload; }, }, effects: (dispatch) => ({ // handle state changes with impure functions. // use async/await for async actions async incrementAsync(payload: number, state) { console.log("This is current root state", state); await new Promise((resolve) => setTimeout(resolve, 1000)); dispatch.count.increment(payload); }, }), });
The following are some features of Rematch:
- Size less than 2kb
- No configuration required
- Reduce Redux boilerplate files
- Built-in side effect support
- React Devtools support
- TypeScript native support
- Support dynamic addition of reducers
- Support hot reload
- Allow Create multiple stores
- Support React Native
- Extensible plug-ins
Rematch’s store still continues some Redux writing methods, but overall it is much more streamlined . It’s also very easy to get started.
【 4. Recoil 】
Recoil
Recoil provides a new state management model— —Atom model, which can better handle complex state logic.
If you need to use Recoil in a component, you can place RecoilRoot somewhere in the parent component. It is best to set it as the root component:
import React from 'react'; import { RecoilRoot, atom, selector, useRecoilState, useRecoilValue, } from 'recoil'; function App() { return ( <RecoilRoot> <CharacterCounter /> </RecoilRoot> ); }
A atom represents a state. Atom can be read and written from any component. The component that reads the atom value implicitly subscribes to the atom, so any update of the atom will cause the component corresponding to the atom to be re-rendered;
To use atom state, useRecoilState needs to be introduced in the component:
const textState = atom({ key: 'textState', // unique ID (with respect to other atoms/selectors) default: '', // default value (aka initial value) }); function CharacterCounter() { return ( <div> <TextInput /> <CharacterCount /> </div> ); } function TextInput() { const [text, setText] = useRecoilState(textState); const onChange = (event) => { setText(event.target.value); }; return ( <div> <input type="text" value={text} onChange={onChange} /> <br /> Echo: {text} </div> ); }
【 5. Hookstate 】
hookState
HookState is also a very simple state management tool library that is intuitive API for you to easily access the state;
Its main features include:
- Create global state
- Create internal State
- Nested state
- Partial state
- Empty state
HookState mainly includes two important Api HookState and useHookState.
If you need other functions, you can refer to other official APIs.
【 6. Jotai 】
Jotai
Jotai is a primitive and flexible state management for React Library. It is similar to Recoil, but has a smaller package size, a more minimalist API, better TypeScript support, wider documentation, and no experimental tags.
With Jotai, you can store state in a single store and use custom hooks to access and update state.
import { atom, useAtom } from 'jotai'; const countAtom = atom(0); function Counter() { const [count, setCount] = useAtom(countAtom); return ( <div> <h1>Count: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(count - 1)}>Decrement</button> </div> ); }
The above is the sample code for using Jotai. Using Jotai is very simple.
【 7. Zustand】
Zustand provides a simple way to manage state in React applications.
Its main features are ease of use and lightweight.
Zustand Code
使用Zustand,你可以將狀態(tài)存儲(chǔ)在一個(gè)單一的store中,并使用自定義的hooks來(lái)訪(fǎng)問(wèn)和更新?tīng)顟B(tài)。這使得狀態(tài)管理變得非常簡(jiǎn)單和直觀(guān)。
import create from 'zustand' const useStore = create((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), decrement: () => set((state) => ({ count: state.count - 1 })), })) function Counter() { const { count, increment, decrement } = useStore() return ( <div> <h1>Count: {count}</h1> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ) }
使用Zustand也非常的簡(jiǎn)單!
在這個(gè)例子中,我們使用?create
?函數(shù)創(chuàng)建了一個(gè)新的store,
并定義了一個(gè)名為?count
?的狀態(tài)和兩個(gè)更新?tīng)顟B(tài)的
函數(shù)?increment
?和?decrement
?。
然后,我們使用?useStore
?自定義 hook 來(lái)訪(fǎng)問(wèn)和更新?tīng)顟B(tài)。
【以上7個(gè)狀態(tài)管理工具各有特點(diǎn)】
考慮到團(tuán)隊(duì)人員技術(shù)的參差不齊,未來(lái)項(xiàng)目的可維護(hù)、延展性;
建議大家選擇入門(mén)簡(jiǎn)單,上手快的工具;
因?yàn)橹白钤缥覀冞x擇的是Redux,現(xiàn)在再回頭看原來(lái)的項(xiàng)目,簡(jiǎn)直難以維護(hù)了。
如果你的團(tuán)隊(duì)還是傾向于Redux,這里建議還是使用Rematch比較好。
如果是還沒(méi)使用狀態(tài)管理,又想用的,建議使用mobx吧!
(學(xué)習(xí)視頻分享:編程基礎(chǔ)視頻)
The above is the detailed content of [Organization and sharing] 7 popular React state management tools. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The React ecosystem includes state management libraries (such as Redux), routing libraries (such as ReactRouter), UI component libraries (such as Material-UI), testing tools (such as Jest), and building tools (such as Webpack). These tools work together to help developers develop and maintain applications efficiently, improve code quality and development efficiency.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

React is a JavaScript library developed by Meta for building user interfaces, with its core being component development and virtual DOM technology. 1. Component and state management: React manages state through components (functions or classes) and Hooks (such as useState), improving code reusability and maintenance. 2. Virtual DOM and performance optimization: Through virtual DOM, React efficiently updates the real DOM to improve performance. 3. Life cycle and Hooks: Hooks (such as useEffect) allow function components to manage life cycles and perform side-effect operations. 4. Usage example: From basic HelloWorld components to advanced global state management (useContext and

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

The advantages of React are its flexibility and efficiency, which are reflected in: 1) Component-based design improves code reusability; 2) Virtual DOM technology optimizes performance, especially when handling large amounts of data updates; 3) The rich ecosystem provides a large number of third-party libraries and tools. By understanding how React works and uses examples, you can master its core concepts and best practices to build an efficient, maintainable user interface.

React's main functions include componentized thinking, state management and virtual DOM. 1) The idea of ??componentization allows splitting the UI into reusable parts to improve code readability and maintainability. 2) State management manages dynamic data through state and props, and changes trigger UI updates. 3) Virtual DOM optimization performance, update the UI through the calculation of the minimum operation of DOM replica in memory.

React is a JavaScript library developed by Facebook for building user interfaces. 1. It adopts componentized and virtual DOM technology to improve the efficiency and performance of UI development. 2. The core concepts of React include componentization, state management (such as useState and useEffect) and the working principle of virtual DOM. 3. In practical applications, React supports from basic component rendering to advanced asynchronous data processing. 4. Common errors such as forgetting to add key attributes or incorrect status updates can be debugged through ReactDevTools and logs. 5. Performance optimization and best practices include using React.memo, code segmentation and keeping code readable and maintaining dependability

Using HTML to render components and data in React can be achieved through the following steps: Using JSX syntax: React uses JSX syntax to embed HTML structures into JavaScript code, and operates the DOM after compilation. Components are combined with HTML: React components pass data through props and dynamically generate HTML content, such as. Data flow management: React's data flow is one-way, passed from the parent component to the child component, ensuring that the data flow is controllable, such as App components passing name to Greeting. Basic usage example: Use map function to render a list, you need to add a key attribute, such as rendering a fruit list. Advanced usage example: Use the useState hook to manage state and implement dynamics
