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>
    }
  • 相关阅读:
    通用js模块02:validutils.js
    通用js模块04:cookieUtils.js
    通用js模块03:formatutils.js
    通用js模块01:stringutils.js
    应用开发平台与代码生成工具感想
    linq to sql 中isnumeric的使用
    很惭愧啊
    错误:”未能加载文件或程序集“System.Web.Mvc, Version=2.0.0.0” 解决方法
    今天又温习了一下磁盘阵列的概念
    ashx的说明
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12901080.html
Copyright © 2011-2022 走看看