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>
    }
  • 相关阅读:
    在其他机器上安装mysql和hive后设置hive元数据存储为mysql
    MapReduce作业切片和Shuffle
    sns 批量清除脚本
    PHP 汉字 转换成 拼音
    PHPCMS V9 和其他应用同步
    nginx启动,重启,关闭命令
    Linux下zip unzip的用户示例 解压到指定目录
    nginx phpcms rewrite规则
    javascript 里面嵌套方法
    数制及其转换
  • 原文地址:https://www.cnblogs.com/Answer1215/p/12901080.html
Copyright © 2011-2022 走看看