[React Recoil] Use selectors to calculate derived data based on state stored within a Recoil atom
Recoil allows us to use atoms in order to store pieces of state. More often than not in our apps we need to use data that derives from our application state (for instance to multiply height and width stored within a state to calculate area of an element).
Luckily Recoil provides us with a powerful tool to automatically re-calculate derived state value whenever an piece of state changes - selectors.
A selector is a pure function that accepts atoms or other selectors as input. When these upstream atoms or selectors are updated, the selector function will be re-evaluated.
In this quick lesson we're going to learn how to use a selector in order to automatically calculate a square of a number whenever a value stored within an atom is going to change
import React from "react"; import { RecoilRoot, atom, selector, useRecoilState, useRecoilValue, } from "recoil"; import "./App.css"; const numState = atom({ key: "numState", default: 0, }); const squareState = selector({ key: "squareState", get: ({ get }) => { return get(numState) ** 2; }, }); function Counter() { const [number, setNumber] = useRecoilState( numState ); return ( <button onClick={() => setNumber(number + 1)} > Increment! </button> ); } function Square() { const squareNumber = useRecoilValue( squareState ); return <div>Square: {squareNumber}</div>; } function Display() { const number = useRecoilValue(numState); return <div>Number: {number}</div>; } function App() { return ( <RecoilRoot> <div className="App"> <h1>Recoil!</h1> <Counter /> <Display /> <Square /> </div> </RecoilRoot> ); } export default App;
相关文章
- React saga_react获取子组件ref
- React报错之Property 'X' does not exist on type 'HTMLElement'
- the driver is not supported on_GetPeDriver
- insert into on duplicate key_mysql数据库同步解决方案
- react的jsx和React.createElement是什么关系?面试常问_2023-02-27
- 从react源码角度看React-Hydrate原理
- 【论文阅读】Temporal knowledge graph reasoning based on evolutional representation learning
- ORA-23626: No eligible index on table string.string ORACLE 报错 故障修复 远程处理
- ORA-30038: Cannot perform parallel insert on non-partitioned object ORACLE 报错 故障修复 远程处理
- ORA-54036: cannot define referential constraint with ON DELETE SET NULL clause on virtual column ORACLE 报错 故障修复 远程处理
- ORA-55619: Invalid privilege to grant on Flashback Archive ORACLE 报错 故障修复 远程处理
- MySQL Error number: MY-013878; Symbol: ER_IB_MSG_LOG_FILES_RESIZE_ON_START_FAILED__UNEXPECTED; SQLSTATE: HY000 报错 故障修复 远程处理
- mysql replace into和on duplicate key update用法详解数据库
- 深入理解MySQL中的ON用法(mysql 中on用法)
- MySQL中如何使用ON语句(mysql中 on怎么用)
- MySQL中使用ON子句进行精准查询(mysql中on子句查询)
- Oracle中ON关键字的精彩运用(oracle中on的使用)
- Oracle数据库中ON关键字的使用方法(oracle中on怎么用)
- 使用Oracle On关键字实现数据库连接(oracle on关键字)