談?wù)?React 5種非常流行的狀態(tài)管理庫
原文:sourl.cn/F95CrZ,代碼倉庫地址: https://github.com/dabit3/react-state-5-ways
在 React 中,似乎有無數(shù)種處理狀態(tài)管理的方法。想要了解各種庫,去比較它們之間的如何選擇以及它們?nèi)绾卧鞫际且患钊祟^疼的事情。
當(dāng)我學(xué)習(xí)一些新東西時,喜歡去比較那些實(shí)現(xiàn)相同功能的庫,這有助于我理解各種庫之間的差別,并且能夠形成一個自己在構(gòu)建應(yīng)用的時候如何選擇使用它們的思維模型。
在本文中,我將一一介紹如何在 React App 中使用 5 種最流行的庫/APIS(使用最現(xiàn)代和最新版本的庫)如何在 React App程序中使用全局狀態(tài)管理,并且達(dá)到一樣的效果。
- Recoil[1]
- MobX[2]
- XState[3]
- Redux (with hooks)[4]
- Context[5]
我還將試著解釋它們之間的差異,本文以 概述 - 代碼 - 結(jié)論的方式講解。
為了演示 APIS,我們將使用這些庫來做一個如何創(chuàng)建和展示筆記的應(yīng)用。
入門
如果你準(zhǔn)備好了,那么請先創(chuàng)建一個新的 React App,我們將使用它來開始我們的實(shí)踐:
- npx create-react-app react-state-examples
- cd react-state-examples
無論何時何地,使用 start 命令啟動你的命令。
- npm start
Recoil
Recoil Docs[6]
代碼行數(shù):30
我最喜歡 Recoil 的點(diǎn)是因?yàn)樗?Hooks 的 API 以及它的直觀性。
與其他一些庫相比,我想說 Recoil 的和 API 比大多數(shù)庫更容易。
Recoil 實(shí)踐
開始使用Recoil前,先安裝依賴:
- npm install recoil
接下來,將 RecoilRoot 添加到 App 程序的根/入口點(diǎn):
- import App from './App'
- import { RecoilRoot } from 'recoil'
- export default function Main() {
- return (
- <RecoilRoot>
- <App />
- </RecoilRoot>
- );
- }
下一步,要創(chuàng)建一些狀態(tài),我們將使用來自Recoil 的 atom 并設(shè)置key和一些初始狀態(tài):
- import { atom } from 'recoil'
- const notesState = atom({
- key: 'notesState', // unique ID (with respect to other atoms/selectors)
- default: [], // default value (aka initial state)
- });
現(xiàn)在,你可以在你app的任何位置使用來自 Recoil 的useRecoilState。這是使用 Recoil 實(shí)現(xiàn)的筆記 App:
- 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 (
- <RecoilRoot>
- <App />
- </RecoilRoot>
- );
- }
- function App() {
- const [notes, setNotes] = useRecoilState(notesState);
- const [input, setInput] = useState('')
- function createNote() {
- const notesArray = [...notes, input]
- setNotes(notesArray)
- setInput('')
- }
- return (
- <div>
- <h1>My notes app</h1>
- <button onClick={createNote}>Create Note</button>
- <input value={input} onChange={e => setInput(e.target.value)} />
- { notes.map(note => <p key={note}>Note: {note}</p>) }
- </div>
- );
- }
Recoil selectors
來自文檔
selectors 用于計(jì)算基于 state 的派生屬性。這能讓我們避免冗余 state,通常無需使用 reducers 來保持狀態(tài)同步和有效。相反,最小狀態(tài)集存儲在 atoms 中。
使用 Recoil selectors,你可以根據(jù) state 計(jì)算派生屬性,例如,可能是已過濾的待辦事項(xiàng)數(shù)組(在todo app 中)或已發(fā)貨的訂單數(shù)組(在電子商務(wù)應(yīng)用程序中):
- 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)
結(jié)論
recoil 文檔說:"Recoil 是一個用于 React 狀態(tài)管理的實(shí)驗(yàn)性使用工具集。" 當(dāng)我決定在生產(chǎn)環(huán)境中使用庫時,聽到"實(shí)驗(yàn)性"可能會非常擔(dān)心,所以至少在此刻,我不確定我現(xiàn)在對使用 Recoil 的感覺如何 。
Recoil 很棒,我會為我的下一個 app 使用上它,但是擔(dān)心實(shí)驗(yàn)性屬性,因此我將密切關(guān)注它,但現(xiàn)在不將它用于生產(chǎn)中。
Mobx
MobX React Lite Docs[7]
代碼行數(shù): 30
因?yàn)槲以谑褂?Redux 之后使用了MobX React, 所以它一直是我最喜歡的管理 React 狀態(tài)庫之一。多年來,兩者之間的明顯差異,但是對我而言我不會改變我的選擇。
MobX React 現(xiàn)在有一個輕量級版本(MobX React Lite),這個版本專門針對函數(shù)組件而誕生,它的有點(diǎn)是速度更快,更小。
MobX 具有可觀察者和觀察者的概念,然而可觀察的API有所改變,那就是不必指定希望被觀察的每個項(xiàng),而是可以使用 makeAutoObservable 來為你處理所有事情。
如果你希望數(shù)據(jù)是響應(yīng)的并且需要修改 store ,則可以用observer來包裝組件。
MobX 實(shí)踐
開始使用Mobx前,先安裝依賴:
- npm install mobx mobx-react-lite
該應(yīng)用的狀態(tài)已在 Store 中創(chuàng)建和管理。
我們應(yīng)用的 store 如下所示:
- 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()
然后,我們可以導(dǎo)入notes,并在 app 中的任何位置使用它們。要使組件是可觀察修改,需要將其包裝在observer中:
- import { observer } from 'mobx-react-lite'
- import { notes } from './NoteStore'
- const App = observer(() => <h1>{notes[0]|| "No notes"}</h1>)
讓我們看看它們?nèi)绾我黄疬\(yùn)行的:
- 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 (
- <div>
- <h1>My notes app</h1>
- <button onClick={onCreateNote}>Create Note</button>
- <input value={input} onChange={e => setInput(e.target.value)} />
- { notes.map(note => <p key={note}>Note: {note}</p>) }
- </div>
- )
- })
- export default App
總結(jié)
MobX 已經(jīng)誕生了一段時間,它很好用。與許多其他公司一樣,我在企業(yè)公司的大量線上應(yīng)用中使用了它。
最近再次使用它之后的感受是,與其他一些庫相比,我覺得文檔略有不足。我會自己再嘗試一下,然后再做決定。
XState
XState Docs[8]
代碼行數(shù):44
XState 試圖解決現(xiàn)代UI復(fù)雜性的問題,并且依賴于有限狀態(tài)機(jī)[9]的思想和實(shí)現(xiàn)。
XState 是由 David Khourshid[10], 創(chuàng)建的,自發(fā)布以來,我就看到過很多關(guān)于它的討論,所以我一直在觀望。這是在寫本文之前唯一不熟悉的庫。
在使用之后,我可以肯定地說它的實(shí)現(xiàn)方式是與其他庫截然不同的。它的復(fù)雜性比其他任何一種都要高,但是關(guān)于狀態(tài)如何工作的思維模型確實(shí)很 cool 而且對于提高能力很有幫助,在用它構(gòu)建一些 demo app 之后,讓我感到它很精妙。
要了解有關(guān) XState 試圖解決的問題的更多信息,請查看David Khourshid的這段視頻[11]或我也發(fā)現(xiàn)有趣的帖子[12]。
XState 在這里的使用不是特別好,因?yàn)樗m合在更復(fù)雜的狀態(tài)下使用,但是這個簡短的介紹至少可以希望為你提供一個選擇,以幫助你全面了解其工作原理。
XState實(shí)踐
要開始使用XState,請安裝這些庫:
- npm install xstate @xstate/react
要創(chuàng)建machine,請使用xstate中的Machine實(shí)用程序。這是我們將用于 Notes app 的machine:
- 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]
- })
- ]
- }
- }
- })
我們將使用的數(shù)據(jù)存儲在 context 中。在這里,我們有一個 notes 列表 和一個 input 輸入框。有兩種操作,一種用于創(chuàng)建 note(CREATE_NOTE),另一種用于設(shè)置 input(CHANGE)。
整個示例:
- 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 (
- <div>
- <h1>My notes app</h1>
- <button onClick={() => send({ type: 'CREATE_NOTE' })}>Create Note</button>
- <input value={note} onChange={e => send({ type: 'CHANGE', value: e.target.value})} />
- { notes.map(note => <p key={note}>Note: {note}</p>) }
- </div>
- )
- }
要在應(yīng)用中修改狀態(tài),我們使用 xstate-react 中的 useService hooks。
總結(jié)
XState 就像勞斯萊斯 或者說 狀態(tài)管理的瑞士軍刀??梢宰龊芏嗍虑?,但是所有功能都帶來額外的復(fù)雜性。
我希望將來能更好地學(xué)習(xí)和理解它,這樣我就可以將它應(yīng)用到 AWS 的相關(guān)問題和參考它的架構(gòu),但是對于小型項(xiàng)目,我認(rèn)為這可能它太過龐大。
Redux
React Redux docs[13]
代碼行數(shù):33
Redux 是整個 React 生態(tài)系統(tǒng)中最早,最成功的狀態(tài)管理庫之一。我已經(jīng)在許多項(xiàng)目中使用過Redux,如今它依然很強(qiáng)大。
新的 Redux Hooks API 使 redux 使用起來不再那么麻煩,而且使用起來也更容易。
Redux Toolkit 還改進(jìn)了 Redux,并大大降低了學(xué)習(xí)曲線。
Redux 實(shí)踐
開始使用Redux前,先安裝依賴:
- npm install @reduxjs-toolkit react-redux
要使用 Redux,您需要創(chuàng)建和配置以下內(nèi)容:
A store
Reducers
A provider
為了幫助解釋所有這些工作原理,我在實(shí)現(xiàn) Redux 中的 Notes app 的代碼中做了注釋:
- 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 允許你檢索你想使用的狀態(tài),在我們的例子中是notes數(shù)組。 */
- const notes = useSelector(state => state.notes)
- /* dispatch 允許我們向 store 發(fā)送更新信息 */
- const dispatch = useDispatch()
- function onCreateNote() {
- dispatch({ type: 'CREATE_NOTE', note: input })
- setInput('')
- }
- return (
- <div>
- <h1>My notes app</h1>
- <button onClick={onCreateNote}>Create Note</button>
- <input value={input} onChange={e => setInput(e.target.value)} />
- { notes.map(note => <p key={note}>Note: {note}</p>) }
- </div>
- );
- }
- /* 在這里,我們創(chuàng)建了一個 reducer,它將在`CREATE_NOTE`動作被觸發(fā)時更新note數(shù)組。 */
- 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 (
- /* 在這里,我們使用app中的reducer來創(chuàng)建store。 */
- <Provider store={store}>
- <App />
- </Provider>
- )
- }
- export default Main
總結(jié)
如果你正在尋找一個具有龐大社區(qū)、大量文檔以及大量問答的庫,那么Redux是一個非??孔V的選擇。因?yàn)樗颜Q生了很長時間,你只要在 Google 搜索,或多或少都能找到一些相關(guān)的答案。
在使用異步操作(例如數(shù)據(jù)獲取)時,通常需要添加其他中間件,這會增加它的成本和復(fù)雜性。
對我來說,Redux 起初很難學(xué)習(xí)。一旦我熟悉了框架,就可以很容易地使用和理解它。過去,對于新開發(fā)人員而言,有時會感到不知所措,但是隨著 Redux Hooks 和 Redux Toolkit 的改進(jìn),學(xué)習(xí)過程變得容易得多,我仍然強(qiáng)烈建議 Redux 作為前置的選擇。
Context
Context docs[14]
代碼行數(shù): 31
context 的優(yōu)點(diǎn)在于,不需要安裝和依賴其他庫,它是 React 的一部分。
使用 context 非常簡單,當(dāng)你嘗試管理大量不同的 context 值時,問題通常會出現(xiàn)在一些大或者復(fù)雜的應(yīng)用程序中,因此你通常必須構(gòu)建自己的抽象來自己管理這些情況。
Context 實(shí)踐
要創(chuàng)建和使用 context ,請直接從React導(dǎo)入鉤子。下面是它的工作原理:
- /* 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 */
- <NotesContext.Provider value={{ notes: ['note1', 'note2'] }}>
- <App />
- </NotesContext.Provider>
- /* 4. Use the context */
- const { notes } = useContext(NotesContext);
全部代碼
- 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 (
- <NotesContext.Provider value={{ notes, createNote }}>
- <App />
- </NotesContext.Provider>
- );
- }
- function App() {
- const { notes, createNote } = useContext(NotesContext);
- const [input, setInput] = useState('')
- function onCreateNote() {
- createNote(input)
- setInput('')
- }
- return (
- <div>
- <h1>My notes app</h1>
- <button onClick={onCreateNote}>Create Note</button>
- <input value={input} onChange={e => setInput(e.target.value)} />
- { notes.map(note => <p key={note}>Note: {note}</p>) }
- </div>
- );
- }
總結(jié)
context 是一種管理 app 狀態(tài)的真正可靠且直接的方法。它的API可能不如其他一些庫那么好,但是如果你了解如何使用它,并且可以在你的 app 中使用它創(chuàng)建正確的數(shù)據(jù)抽象,那么選擇 context 來管理你的全局狀態(tài)就不會錯。
參考資料
[1]Recoil: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#recoil
[2]MobX: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#mobx
[3]XState: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#xstate
[4]Redux (with hooks): https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#redux
[5]Context: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#context
[6]Recoil Docs: https://recoiljs.org/
[7]MobX React Lite Docs: https://github.com/mobxjs/mobx-react-lite
[8]XState Docs: https://xstate.js.org/docs/packages/xstate-react/
[9]有限狀態(tài)機(jī): https://en.wikipedia.org/wiki/Finite-state_machine
[10]David Khourshid: https://twitter.com/DavidKPiano
[11]這段視頻: https://www.youtube.com/watch?v=RqTxtOXcv8Y
[12]帖子: https://dev.to/hectorleiva/how-writing-state-machines-made-me-feel-like-a-programmer-2ndc
[13]React Redux docs: https://react-redux.js.org/
[14]Context docs: https://reactjs.org/docs/hooks-reference.html#usecontext
本文轉(zhuǎn)載自微信公眾號「 秋風(fēng)的筆記」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系 秋風(fēng)的筆記公眾號。