current position:Home>React's state management library recoil

React's state management library recoil

2021-08-25 00:21:29 JackySummer

Why use Recoil

Before learning something , We have to understand why it was born , Or what problem it solves .

Recoil By Facebook A brand new 、 Experimental JavaScript State Management Library , It solves the problem of using existing Context API Many problems in building large applications .

Use React The built-in state management capability has some limitations :

  • State sharing between components can only be achieved by state Ascend to their common ancestors to achieve , But doing so may result in re rendering a huge component tree .
  • Context Only a single value can be stored , Cannot store multiple files owned by each Consumer The set of values of .
  • Both of the above methods are difficult to the top of the component tree (state Where it must exist ) And leaf assembly ( Use state The place of ) Code segmentation .

Even though it's like Redux and MobX Such a library ensures that the state of the application is consistent , But for many applications , The cost they bring is incalculable .

Redux、Mobx Not in itself React library , We use the capabilities of these libraries to realize state management . image Redux Although it itself provides a powerful state management capability , But the cost of using is very high , You also need to write a lot of lengthy code , In addition, asynchronous processing or cache computing are not the capabilities of these libraries themselves , You even need to use other external libraries .

also , They don't have access to React Internal scheduler , and Recoil Use in the background React In its own state , In the future, it can also provide the ability of concurrency mode

Recoil What is it?

Facebook Our software engineers have made such a speech to share

to update List The second node , Then hope Canvas The second node of is also updated .

image.png

The oldest way is to communicate through a common parent-child component , But the child components under the parent component will be updated , In this case, it is generally used  memo  perhaps  PureComponent.

You can also use React Self contained Context API, Pass state from parent component to child component .

But the problem is that if we share more states, we need more Provider, Layer upon layer .

image.png

Is there a way to accurately update nodes , At the same time, there is no need to nest too many levels of schemes ? It is Recoil. By creating orthogonal tree, Each one state Corresponding to components , So as to achieve accurate update .

Recoil Will these state be called Atom( Atom ), seeing the name of a thing one thinks of its function ,Atom yes Recoil The smallest data unit in it , It supports updates and subscriptions .

image.png

Use

First look at it. Recoil How is it used

The root component

Use recoil Components in state need to use RecoilRoot Wrap it up , Generally, the root component is wrapped directly

import React from 'react'
import ReactDOM from 'react-dom'
import { RecoilRoot } from 'recoil'
import App from './App'

ReactDOM.render(
  <RecoilRoot>
    <App />
  </RecoilRoot>,
  document.getElementById('root')
)

Atoms

Atom Is the smallest state unit . They can be subscribed and updated : When it updates , All components that subscribe to it will redraw with the new data ; It can be created at run time ; It can also be used in local states ; The same Atom Can be used and shared by multiple components .

comparison Redux Maintain the global Store,Recoil It adopts the design mode of decentralized management of atomic state , Facilitate code segmentation .

Atom And traditional state Different , It can be subscribed to by any component , When one Atom When updated , Each subscribed component will be re rendered with the new value .

therefore Atom Equivalent to a group of state Set , Change one Atom Only specific subcomponents will be rendered , The entire parent component will not be re rendered .

import { atom } from 'recoil'

export const todoList = atom({
  key: 'todoList',
  default: [],
})

To create a Atom , A must be provided key , It has to be in RecoilRoot Is unique in the scope , And provide a default value , The default value can be a static value 、 The function can even be an asynchronous function .

API

Recoil use Hooks Way to subscribe and update status , frequently-used API as follows :

useRecoilState

similar useState One of the Hook, It can be done to atom To read and write

import React, { useState } from 'react'
import { useRecoilState } from 'recoil'
import { TodoListStore } from './store'

export default function OperatePanel() {
  const [inputValue, setInputValue] = useState('')
  const [todoListData, setTodoListData] = useRecoilState(TodoListStore.todoList)

  const addItem = () => {
    const newList = [...todoListData, { thing: inputValue, isComplete: false }]
    setTodoListData(newList)
    setInputValue('')
  }

  return (
    <div>
      <h3>OperatePanel Page</h3>
      <input type='text' value={inputValue} onChange={e => setInputValue(e.target.value)} />
      <button onClick={addItem}> add to </button>
    </div>
  )
}

useSetRecoilState

Get only setter function , Will not return state Value , If only this function is used , State changes do not cause components to re render

import React from 'react'
import { useSetRecoilState } from 'recoil'
import { TodoListStore } from './store'
export default function SetPanel() {
  const setTodoListData = useSetRecoilState(TodoListStore.todoList)

  const clearData = () => {
    setTodoListData([])
  }

  return (
    <div>
      <button onClick={clearData}> Empty recoil Array of </button>
    </div>
  )
}

useRecoilValue

Only return state Value , No modification method is provided

import React from 'react'
import { useRecoilValue } from 'recoil'
import { TodoListStore } from './store'
export default function ShowPanel() {
  const todoListData = useRecoilValue(TodoListStore.todoList)
  return (
    <div>
      <h3>ShowPanel Page</h3>
      recoil Get the results and show :
      {todoListData.map((item, index) => {
        return <div key={index}>{item.thing}</div>
      })}
    </div>
  )
}

selector

selector Represents a derived state , It enables us to build dependence on other atom The state of . It has a mandatory get function , Its function and redux Of reselect or MobX Of computed similar .

selector It's a pure function : For a given set of inputs , They should always produce the same results ( At least for the lifetime of the application ). This is important , Because the selector may execute one or more times , May restart and may be cached .

export const completeCountSelector = selector({
  key: 'completeCountSelector',
  get({ get }) {
    const completedList = get(todoList)
    return completedList.filter(item => item.isComplete).length
  },
})

selector Asynchronous functions are also supported , You can put a Promise As return value

Conclusion

except Facebook, I haven't seen which websites have been used yet Recoil.

Recoil The core concepts are simple , No, Redux So, the concept of detour , There's no need to write a bunch of things like action、reducer And so on , be based on Hooks Of API And its intuitiveness . Compared with some other libraries ,Recoil Of API Easier than most libraries , Make development easier .

Our current project uses Recoil, The current feeling is a simplified version Context API, Use the Redux Simple , I haven't found anything like Redux The convenient time tracing function of Ecology , The follow-up use remains to be observed .

This article case code


copyright notice
author[JackySummer],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825002125592u.html

Random recommended