[React Recoil] Use a Recoil atom to share state between two React components
React to use State two between Components share
2023-09-14 09:00:47 时间
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] Use React.memo with a Function Component to get PureComponent Behavior
- [React] How to use a setState Updater Function with a Reducer Pattern
- [Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose
- [Recompose] Stream Props to React Children with RxJS
- [React Router v4] Redirect to Another Page
- [XState + React] using @xstate/inspect to display state machine char in webapp
- [React] Use the React Context API to Globally Manage State
- [React Testing] Using __mocks__ to mock the promise based API
- [React] useMemo and React.memo
- [React] When to useReducer instead of useState
- [React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks
- [React] Simplify and Convert a Traditional React Form to Formik
- [React] Refactor a connected Redux component to use Unstated
- [Mobx] Using mobx to isolate a React component state
- [React Intl] Use a react-intl Higher Order Component to format messages
- React/React Native 的ES5 ES6写法对照表