Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the very popular state management library for React5?

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is to explain "what are the five very popular state management libraries of React". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what are the five very popular state management libraries of React?"

If you are ready, create a new React App first, and we will use it to start our practice:

Npx create-react-app react-state-examples cd react-state-examples

Whenever and wherever, use the start command to start your command.

Npm start

Recoil

Recoil Docs [6]

Lines of code: 30

What I like most about Recoil is that it is based on Hooks's API and its intuition.

Compared to some other libraries, I would say that Recoil's and API are easier than most.

Recoil practice

Before you start using Recoil, install dependencies:

Npm install recoil

Next, add RecoilRoot to the root / entry point of the App program:

Import App from'. / App' import {RecoilRoot} from 'recoil' export default function Main () {return ();}

Next, to create some states, we will use atom from Recoil and set up key and some initial states:

Import {atom} from 'recoil' const notesState = atom ({key:' notesState', / / unique ID (with respect to other atoms/selectors) default: [], / / default value (aka initial state)})

Now, you can use useRecoilState from Recoil anywhere in your app. This is a note App implemented using Recoil:

Import React, {useState} from 'react'; import {RecoilRoot, atom, useRecoilState} from' recoil'; const notesState = atom ({key: 'notesState', / / unique ID (with respect to other atoms/selectors) default: [], / / default value (aka initial state)}); export default function Main () {return ();} function App () {const [notes, setNotes] = useRecoilState (notesState) Const [input, setInput] = useState ('') function createNote () {const notesArray = [... notes, input] setNotes (notesArray) setInput ('')} return (My notes app Create Note setInput (e.target.value)} / > {notes.map (note = > Note: {note})

)})

Recoil selectors

From document

Selectors is used to calculate derived attributes based on state. This allows us to avoid redundant state, usually without the need to use reducers to keep the state synchronized and efficient. Instead, the minimum state set is stored in atoms.

Using Recoil selectors, you can calculate derived properties based on state, for example, an array of filtered to-do items (in todo app) or an array of shipped orders (in e-commerce applications):

Import {selector, useRecoilValue} from 'recoil' const completedTodosState = selector ({key:' todosState', get: ({get}) = > {const todos = get (todosState) return todos.filter (todo = > todo.completed)}}) const completedTodos = useRecoilValue (completedTodosState)

Conclusion

The recoil documentation says: "Recoil is an experimental toolset for React state management." When I decide to use libraries in a production environment, I may be very worried to hear "experimental", so at least for the moment, I'm not sure how I feel about using Recoil.

Recoil is great, and I'll use it for my next app, but I'm worried about experimental properties, so I'll keep a close eye on it, but I won't use it in production right now.

Mobx

MobX React Lite Docs [7]

Lines of code: 30

Because I used MobX React after using Redux, it has always been one of my favorite state libraries for managing React. There has been an obvious difference between the two over the years, but as far as I am concerned, I will not change my choice.

MobX React now has a lightweight version (MobX React Lite), which is designed specifically for functional components, but it is a little faster and smaller.

MobX has the concept of observer and observer, but the observable API has changed, that is, instead of specifying every item you want to be observed, you can use makeAutoObservable to handle everything for you.

If you want the data to be responsive and need to modify the store, you can use observer to wrap the component.

MobX practice

Before you start using Mobx, install dependencies:

Npm install mobx mobx-react-lite

The status of the application has been created and managed in Store.

The store we applied is as follows:

Import {makeAutoObservable} from 'mobx' class NoteStore {notes = [] createNote (note) {this.notes = [... this.notes, note]} constructor () {/ * makes all data in store observable, replaces @ observable * / makeAutoObservable (this)}} const Notes = new NoteStore ()

We can then import notes and use them anywhere in app. To make the component observable, you need to wrap it in an observer:

Import {observer} from 'mobx-react-lite' import {notes} from'. / NoteStore' const App = observer (() = > {notes [0] | | "No notes"})

Let's see how they work together:

Import React, {useState} from 'react' import {observer} from "mobx-react-lite" import {makeAutoObservable} from' mobx' class NoteStore {notes = [] createNote (note) {this.notes = [... this.notes, note]} constructor () {makeAutoObservable (this)} const Notes = new NoteStore () const App = observer (() = > {const [input) SetInput] = useState ('') const {notes} = Notes function onCreateNote () {Notes.createNote (input) setInput ('')} return (My notes app CreateNote setInput (e.target.value)} / > {notes.map (note = > Note: {note})

)})}) export default App

Summary

MobX has been around for some time, and it's easy to use. Like many other companies, I use it in a large number of online applications in enterprise companies.

The feeling after using it again recently is that compared with some other libraries, I think the documentation is slightly inadequate. I will try again by myself and then make a decision.

XState

XState Docs [8]

Lines of code: 44

XState tries to solve the complexity of modern UI and depends on the idea and implementation of finite state machine [9].

XState was created by David Khourshid [10], and I've seen a lot of discussion about it since it was released, so I've been watching. This is the only library you are not familiar with before writing this article.

After using it, I can say for sure that it is implemented in a very different way from other libraries. It's more complex than any other, but the thought model of how the state works is really cool and helpful in improving capabilities, and it makes me feel subtle after building some demo app with it.

To learn more about the problem XState is trying to solve, check out this video of David Khourshid [11] or I also find interesting posts [12].

XState doesn't work particularly well here because it's more suitable for more complex situations, but at least this brief introduction hopes to give you a choice to help you fully understand how it works.

XState practice

To get started with XState, install these libraries:

Npm install xstate @ xstate/react

To create a machine, use the Machine utility in xstate. This is the machine we will use for Notes app:

Import {Machine} from 'xstate' const notesMachine = Machine ({id:' notes', initial: 'ready', context: {notes: [], note:'}, states: {ready: {},}, on: {"CHANGE": {actions: [assign ({note: (_) Event) = > event.value})}, "CREATE_NOTE": {actions: [assign ({note: ", notes: context = > [... context.notes, context.note]})})

The data we use is stored in context. Here, we have a notes list and an input input box. There are two operations, one for creating note (CREATE_NOTE) and the other for setting up input (CHANGE).

The whole example:

Import React from 'react' import {useService} from' @ xstate/react' import {Machine, assign, interpret} from 'xstate' const notesMachine = Machine ({id:' notes', initial: 'ready', context: {notes: [], note:'}, states: {ready: {},}, on: {"CHANGE": {actions: [assign ({note: (_) Event) = > event.value})}, "CREATE_NOTE": {actions: [assign ({note: ", notes: context = > [... context.notes, context.note]})}}) const service = interpret (notesMachine). Start () export default function App () {const [state Send] = useService (service) const {context: {note, notes}} = state return ({type: 'CREATE_NOTE'})} > Create Note send ({type:' CHANGE', value: e.target.value})} / > {notes.map (note = > Note: {note})

)})}

To modify the state in the application, we use useService hooks in xstate-react.

Summary

XState is like a Rolls-Royce or Swiss Army knife for state management. There are many things that can be done, but all the features bring additional complexity.

I hope to learn and understand it better in the future so that I can apply it to AWS-related issues and refer to its architecture, but for small projects, I think it may be too big.

Redux

React Redux docs [13]

Lines of code: 33

Redux is one of the earliest and most successful state management libraries in the whole React ecosystem. I have used Redux in many projects, and it is still powerful today.

The new Redux Hooks API makes redux less cumbersome to use and easier to use.

Redux Toolkit also improves Redux and greatly reduces the learning curve.

Redux practice

Before you start using Redux, install dependencies:

Npm install @ reduxjs-toolkit react-redux

To use Redux, you need to create and configure the following:

A store

Reducers

A provider

To help explain all of this, I commented on the code that implements Notes app in Redux:

Import React, {useState} from 'react' import {Provider, useDispatch, useSelector} from' react-redux' import {configureStore, createReducer, combineReducers} from'@ reduxjs/toolkit' function App () {const [input, setInput] = useState ('') / * useSelector allows you to retrieve the status you want to use, in our case notes array. * / const notes = useSelector (state = > state.notes) / * dispatch allows us to send update information to store * / const dispatch = useDispatch () function onCreateNote () {dispatch ({type: 'CREATE_NOTE', note: input}) setInput (')} return (My notes app CreateNote setInput (e.target.value)} / > {notes.map (note = > Note: {note})

)});} / * here, we create a reducer that updates the note array when the `CREATE_ Note` action is triggered. * / const notesReducer = createReducer ([], {'CREATE_NOTE': (state, action) = > [... state, action.note]}) / * Here we create the store using the reducers in the app * / const reducers = combineReducers ({notes: notesReducer}) const store = configureStore ({reducer: reducers}) function Main () {return (/ * here, we use reducer in app to create store. * /)} export default Main

Summary

If you are looking for a library with a large community, a large number of documents, and a large number of questions and answers, then Redux is a very reliable choice. Because it has been around for a long time, you can find some relevant answers more or less as long as you search on Google.

When using asynchronous operations (such as data acquisition), you usually need to add other middleware, which increases its cost and complexity.

For me, Redux was difficult to learn at first. Once I am familiar with the framework, it is easy to use and understand it. In the past, it was sometimes overwhelming for new developers, but with the improvement of Redux Hooks and Redux Toolkit, the learning process has become much easier, and I still strongly recommend Redux as a front-end choice.

Context

Context docs [14]

Lines of code: 31

The advantage of context is that there is no need to install and rely on other libraries, it is part of React.

Using context is very simple, and when you try to manage a large number of different context values, problems often occur in large or complex applications, so you usually have to build your own abstractions to manage these situations yourself.

Context practice

To create and use context, import hooks directly from React. Here's how it works:

/ * 1. Import the context hooks * / import React, {useState, createContext, useContext} from 'react'; / * 2. Create a piece of context * / const NotesContext = createContext (); / * 3. Set the context using a provider * / / * 4. Use the context * / const {notes} = useContext (NotesContext)

All codes

Import React, {useState, createContext, useContext} from 'react'; const NotesContext = createContext (); export default function Main () {const [notes, setNotes] = useState ([]) function createNote (note) {const notesArray = [... notes, note] setNotes (notesArray)} return ();} function App () {const {notes, createNote} = useContext (NotesContext) Const [input, setInput] = useState ('') function onCreateNote () {createNote (input) setInput ('')} return (My notes app CreateNote setInput (e.target.value)} / > {notes.map (note = > Note: {note})

)});} at this point, I believe you have a deeper understanding of "what are the five very popular state management libraries of React". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report