zoukankan      html  css  js  c++  java
  • [React Recoil] Use a Recoil atom to share state between two React components

    Recoil is a brand new state management library for React developed by Facebook.

    In this quick lesson we're going to learn how to add it to a React app and how to use a Recoil atom in order to share state between two React components using useRecoilState hook

    Install:

    yarn add recoil

    App.js:

    We need to wrap the App or where we want to apply state from Recoil within 'RecoilRoot':

    import { RecoilRoot } from 'recoil'
    
    function App() {
      return (
        <RecoilRoot>
          <div className="App">
              <Counter />
              <Display />
          </div>
        </RecoilRoot>
      )
    }

    Counter.js:

    import React from 'react'
    import { atom, useRecoilState } from 'recoil'
    
    const numState = atom({
      key: 'numState',
      default: 0,
    })
    
    export default function Counter() {
      const [number, setNumber] = useRecoilState(numState)
      const upNum = () => setNumber(number + 1)
      return <button onClick={upNum}>{number}</button>
    }

    It can share state throungh 'atom'.

    const numState = atom({
      key: 'numState',
      default: 0,
    })

    Use in multi components:

    export function Display() {
      const [number] = useRecoilState(numState)
      return <h2>{number}</h2>
    }

    Since we don't need to 'setNumber' in "Display" component, we can use 'useRecoilValue':

    import React from 'react'
    import { atom, useRecoilState, useRecoilValue } from 'recoil'
    
    const numState = atom({
      key: 'numState',
      default: 0,
    })
    
    export default function Counter() {
      const [number, setNumber] = useRecoilState(numState)
      const upNum = () => setNumber(number + 1)
      return <button onClick={upNum}>{number}</button>
    }
    
    export function Display() {
      const number = useRecoilValue(numState)
      return <h2>{number}</h2>
    }
  • 相关阅读:
    SVG 2D入门11
    SVG 2D入门13
    jetty
    jquery 跨域访问问题 转
    js 读取 地址栏参数 转
    油猴 greasemonkey 背景音乐 火狐 chrome 背景音乐
    火狐 about:config
    js javascript 模拟点击 超级链接点击 转
    PostgreSQL的时间/日期函数使用 转
    update 多表
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12901080.html
Copyright © 2011-2022 走看看