[React Recoil] Use a Recoil atom to share state between two React components
React to use State two between Components share
2023-09-14 08:59:13 时间
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> }
相关文章
- [React Recoil] Write a Custom Recoil Hook to Reset a Value in the Recoil State
- [React] Use CSS Transitions to Avoid a Flash of Loading State
- [React] Use React.memo with a Function Component to get PureComponent Behavior
- [React] Use React Fragments to make your DOM tree cleaner
- [Poi] Use Markdown as React Components by Adding a Webpack Loader to Poi
- [React Router v4] Redirect to Another Page
- [React] Use React ref to Get a Reference to Specific Components
- [React] React Fundamentals: Introduction to Properties
- [React] Use react styled system with styled components
- [React Recoil] Use a Recoil atom to share state between two React components
- [React Testing] Test your Custom Hook Module with react-hooks-testing-library
- [React] Use React.memo with a Function Component to get PureComponent Behavior
- [React] Forward a DOM reference to another Component using forwardRef in React 16.3
- [React Intl] Use Webpack to Conditionally Include an Intl Polyfill for Older Browsers
- [React] Create an Auto Resizing Virtualized List with react-virtualized
- [React Fundamentals] Using Refs to Access Components
- [React] Intro to inline styles in React components