Home  >  Article  >  Web Front-end  >  [Organization and sharing] 7 popular React state management tools

[Organization and sharing] 7 popular React state management tools

青灯夜游
青灯夜游forward
2023-04-26 17:47:482326browse

[Organization and sharing] 7 popular React state management tools

Recently 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`包裹的函数式组件会被监听在它每一次调用前发生的任何变化
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 &#39;redux&#39;

/**
 * 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&#39;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&#39;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&#39;s not required.
 */
function counterReducer(state = { value: 0 }, action) {
  switch (action.type) {
    case &#39;counter/incremented&#39;:
      return { value: state.value + 1 }
    case &#39;counter/decremented&#39;:
      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&#39;d use a view binding library (e.g. React Redux) rather than subscribe() directly.
// There may be additional use cases where it&#39;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: &#39;counter/incremented&#39; })
// {value: 1}
store.dispatch({ type: &#39;counter/incremented&#39; })
// {value: 2}
store.dispatch({ type: &#39;counter/decremented&#39; })
// {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 &#39;react&#39;;
import {
  RecoilRoot,
  atom,
  selector,
  useRecoilState,
  useRecoilValue,
} from &#39;recoil&#39;;

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: &#39;textState&#39;, // unique ID (with respect to other atoms/selectors)
  default: &#39;&#39;, // 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 &#39;jotai&#39;;

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,你可以将状态存储在一个单一的store中,并使用自定义的hooks来访问和更新状态。这使得状态管理变得非常简单和直观。

import create from &#39;zustand&#39;

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也非常的简单!

在这个例子中,我们使用 create 函数创建了一个新的store,

并定义了一个名为 count 的状态和两个更新状态的

函数 increment 和 decrement 。

然后,我们使用 useStore 自定义 hook 来访问和更新状态。

【以上7个状态管理工具各有特点】

考虑到团队人员技术的参差不齐,未来项目的可维护、延展性;

建议大家选择入门简单,上手快的工具;

因为之前最早我们选择的是Redux,现在再回头看原来的项目,简直难以维护了。

如果你的团队还是倾向于Redux,这里建议还是使用Rematch比较好。

如果是还没使用状态管理,又想用的,建议使用mobx吧!

(学习视频分享:编程基础视频

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete