当前位置:网站首页>Usememo simulation usecallback
Usememo simulation usecallback
2022-06-25 07:45:00 【CamilleZJ】
useMemo Cache results ,useCallback Cache function
1、 to glance at useMemo and useCallback Differences in underlying source code
useMemo The source code to achieve
When the component is rendered for the first time useMemo Source code implementation :
// React edition :16.13.1
// react-reconciler/src/ReactFiberHooks.new.js
function mountMemo<T>(
nextCreate: () => T, // “ establish ” function
deps: Array<mixed> | void | null, // Dependencies
): T {
const hook = mountWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
const nextValue = nextCreate(); // perform " establish " function
hook.memoizedState = [nextValue, nextDeps]; // take " establish " function The returned value after execution is cached
return nextValue; // Returns the cached variable value
}
useMemo When the dependencies of change useMemo Source code implementation :
// React edition :16.13.1
// react-reconciler/src/ReactFiberHooks.new.js
function updateMemo<T>(
nextCreate: () => T,
deps: Array<mixed> | void | null,
): T {
const hook = updateWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
const prevState = hook.memoizedState;
if (prevState !== null) {
// Assume these are defined. If they're not, areHookInputsEqual will warn.
if (nextDeps !== null) {
const prevDeps: Array<mixed> | null = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
const nextValue = nextCreate();
hook.memoizedState = [nextValue, nextDeps];
return nextValue;
}Dependency contrast :
function areHookInputsEqual(nextDeps, prevDeps) {
if (prevDeps === null) {
{
warning$1(false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
}
return false;
}
{
// Don't bother comparing lengths in prod because these arrays should be
// passed inline.
if (nextDeps.length !== prevDeps.length) {
warning$1(false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, '[' + nextDeps.join(', ') + ']', '[' + prevDeps.join(', ') + ']');
}
}
for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
if (is(nextDeps[i], prevDeps[i])) {
continue;
}
return false;
}
return true;
}
/**
* inlined Object.is polyfill to avoid requiring consumers ship their own
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
*/
function is(x, y) {
return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
;
}Be careful : above react Include state and props All comparisons are made with shallowEaque, Compare only one layer . And the dependency is an object X===Y Different objects still have the same content return false, The following cases , Unless the first two useMemo Will not be updated , Otherwise, it will be updated every time ,useEffect And useCallback Empathy ,useMemo Commonly used to cache components , So don't use it indiscriminately useMemo etc. hooks
const [obj, setObj] = useState({a:1})
// Such as clicking, etc state to update
setObj(obj)
setObj(preObj=>preObj)
setObj(preObj=>{...preObj})
useMemo(()=>{....},[obj]useCallback The source code to achieve
When the component is rendered for the first time useCallback Source code implementation :
// React edition :16.13.1
// react-reconciler/src/ReactFiberHooks.new.js
function mountCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
const hook = mountWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
hook.memoizedState = [callback, nextDeps];
return callback;
}
useCallback When the dependencies of change useMemo Source code implementation :
// React edition :16.13.1
// react-reconciler/src/ReactFiberHooks.new.js
function updateCallback<T>(callback: T, deps: Array<mixed> | void | null): T {
const hook = updateWorkInProgressHook();
const nextDeps = deps === undefined ? null : deps;
const prevState = hook.memoizedState;
if (prevState !== null) {
if (nextDeps !== null) {
const prevDeps: Array<mixed> | null = prevState[1];
if (areHookInputsEqual(nextDeps, prevDeps)) {
return prevState[0];
}
}
}
hook.memoizedState = [callback, nextDeps];
return callback;
}useMemo and useCallback Is to return a cached value ,useMemo What is returned is a cached variable , and useCallback What is returned is a cached callback function . Can be in useMemo Of " Create a function " Returns a callback function to simulate useCallback The function of .useMemo and useCallback It can be used to solve the performance problems in the process of function component update .
// Use useCallback Cache function
const addClick = useCallback(() => {
let sum = 0;
for (let i = 0; i < count; i++) {
sum += i;
}
return sum;
}, [count]);
// Use useMemo replace useCallback Cache function
const addClick = useMemo(() => () => {
let sum = 0;
for (let i = 0; i < count; i++) {
sum += i;
}
return sum;
}, [count]);
边栏推荐
- realsense d455 semantic_ Slam implements semantic octree mapping
- What if there is no point in data visualization?
- CGLIB动态代理
- 权限、认证系统相关名词概念
- Shell tips (134) simple keyboard input recorder
- [batch dos-cmd command - summary and summary] - application startup and call, service and process operation commands (start, call, and)
- C Getting Started tutorial
- Chuantu microelectronics 𞓜 subminiature package isolated half duplex 485 transceiver
- VectorDraw Developer Framework 10.10
- Sichuan earth microelectronics ca-is1200 isolated operational amplifier for current detection
猜你喜欢

shell小技巧(一百三十四)简单的键盘输入记录器

Introduction to Sichuan Tuwei ca-is3082wx isolated rs-485/rs-422 transceiver

【蒸馏】PointDistiller: Structured Knowledge DistillationTowards Efficient and Compact 3D Detection

npm install 报错 : gyp ERR! configure error

Estimation of dense forest volume based on LIDAR point cloud with few ground points

Understand the reasons for impedance matching of PCB circuit board 2021-10-07

Find out what informatization is, and let enterprises embark on the right path of transformation and upgrading

Without "rice", you can cook "rice". Strategy for retrieving missing ground points under airborne lidar forest using "point cloud intelligent mapping"
![[batch dos-cmd command - summary and summary] - application startup and call, service and process operation commands (start, call, and)](/img/19/b8c0fb72f1c851a6b97f2c17a18665.png)
[batch dos-cmd command - summary and summary] - application startup and call, service and process operation commands (start, call, and)

The method of judging whether triode can amplify AC signal
随机推荐
CPDA|数据分析师成长之路如何起步?
SSL证书免费获取教程
一“石”二“鸟”,PCA有效改善机载LiDAR林下地面点部分缺失的困局
【批处理DOS-CMD命令-汇总和小结】-CMD窗口的设置与操作命令(cd、title、mode、color、pause、chcp、exit)
[batch dos-cmd command - summary and summary] - file and directory operation commands (MD, RD, xcopy, dir, CD, set, move, copy, del, type, sort)
Distributed quorum NWR of the alchemy furnace of the Supreme Master
This year, I graduated
Without "rice", you can cook "rice". Strategy for retrieving missing ground points under airborne lidar forest using "point cloud intelligent mapping"
Storage of Galileo broadcast ephemeris in rtklib-b33
权限、认证系统相关名词概念
[distillation] pointdistiller: structured knowledge distillationwards efficient and compact 3D detection
SQL solve select basic statement
Runtime——methods成员变量,cache成员变量
C reads XML on the web
数据可视化没有重点怎么办?
三年营收连续下滑,天地壹号困在醋饮料里
Modular programming of wireless transmission module nRF905 controlled by single chip microcomputer
國外LEAD域名郵箱獲取途徑
【批处理DOS-CMD命令-汇总和小结】-cmd扩展命令、扩展功能(cmd /e:on、cmd /e:off)
“空间转换”显著提升陡崖点云的地面点提取质量