自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Ahooks源碼分析之usePersistFn

開發(fā) 前端
官方給的demo中更新textRef寫在了useEffect中,為什么usePersistFn不這樣實現(xiàn)?

usePersistFn

usePersistFn可以持久化function,保證函數(shù)地址永遠不會變化。

import { useRef } from 'react';

export type noop = (...args: any[]) => any;

function usePersistFn<T extends noop>(fn: T) {
const fnRef = useRef<T>(fn);
// 每次渲染fn的最新值都會記錄在fnRef中
fnRef.current = fn;

const persistFn = useRef<T>();
// 初次渲染時給persistFn賦值,此后persistFn不會更新
if (!persistFn.current) {
persistFn.current = function (...args) {
return fnRef.current!.apply(this, args);
} as T;
}

// 返回persistFn,感嘆號表示返回值類型非null或undefined,因為初次渲染時persistFn就被賦值為了函數(shù)
return persistFn.current!;
}

export default usePersistFn;

為什么要用usePersistFn?

在React官方文檔中提到

在某些場景中,你可能會需要用 useCallback 記住一個回調(diào),但由于內(nèi)部函數(shù)必須經(jīng)常重新創(chuàng)建,記憶效果不是很好,導(dǎo)致子組件重復(fù) render。對于超級復(fù)雜的子組件,重新渲染會對性能造成影響。通過 usePersistFn,可以保證函數(shù)地址永遠不會變化。

官方給出的demo如下

function Form() {
const [text, updateText] = useState('');
const textRef = useRef();

useEffect(() => {
textRef.current = text; // 把它寫入 ref
});

const handleSubmit = useCallback(() => {
const currentText = textRef.current; // 從 ref 讀取它
alert(currentText);
}, [textRef]); // 不要像 [text] 那樣重新創(chuàng)建 handleSubmit

return (
<>
<input value={text} onChange={e => updateText(e.target.value)} />
<ExpensiveTree onSubmit={handleSubmit} />
</>
);
}
復(fù)制代碼

ExpensiveTree是一個復(fù)雜的子組件,其接受一個props handleSubmit函數(shù)。如果使用useCallback,由于handleSubmit函數(shù)內(nèi)部使用了text變量,便要寫為如下形式:

const handleSubmit = useCallback(() => {
alert(text);
}, [text]);
復(fù)制代碼

只要text發(fā)生變化,useCallback接收的內(nèi)部函數(shù)便要重新創(chuàng)建,導(dǎo)致handleSubmit函數(shù)的引用地址發(fā)生變化。進而引起子組件ExpensiveTree的重渲染,對性能產(chǎn)生影響。

usePersistFn的目標便是持久化接收的函數(shù),且調(diào)用時內(nèi)部函數(shù)引用的變量(上例為text)能獲取到實時的值(useCallback的依賴傳空數(shù)組也能實現(xiàn)持久化函數(shù),但無法獲取實時的值)

官方給的demo中更新textRef寫在了useEffect中,為什么usePersistFn不這樣實現(xiàn)?

如果在子組件的useEffect回調(diào)函數(shù)中調(diào)用usePersistFn就會出現(xiàn)問題。因為渲染時會先執(zhí)行子組件的useEffect,后執(zhí)行父組件自定義hooks的useEffect。

文章出自:??前端餐廳ReTech??,如有轉(zhuǎn)載本文請聯(lián)系前端餐廳ReTech今日頭條號。

github:??https://github.com/zuopf769??

責任編輯:武曉燕 來源: 今日頭條
相關(guān)推薦

2022-08-16 21:01:56

runAsyncreload數(shù)據(jù)

2022-06-06 08:02:21

ahooks架構(gòu)hooks

2011-05-26 10:05:48

MongoDB

2012-09-20 10:07:29

Nginx源碼分析Web服務(wù)器

2021-07-06 09:29:38

Cobar源碼AST

2021-03-23 09:17:58

SpringMVCHttpServletJavaEE

2024-06-13 07:55:19

2011-05-26 16:18:51

Mongodb

2020-07-28 08:54:39

內(nèi)核通信Netlink

2012-09-06 10:07:26

jQuery

2021-09-05 07:35:58

lifecycleAndroid組件原理

2009-07-08 13:22:30

JDK源碼分析Set

2017-01-12 14:52:03

JVMFinalRefere源碼

2022-08-27 08:02:09

SQL函數(shù)語法

2022-01-06 07:06:52

KubernetesResourceAPI

2022-05-30 07:36:54

vmstoragevmselect

2022-07-01 07:31:18

AhooksDOM場景

2019-09-09 06:30:06

Springboot程序員開發(fā)

2023-03-17 07:53:20

K8sAPIServerKubernetes

2017-02-27 11:48:58

JVM源碼分析Java
點贊
收藏

51CTO技術(shù)棧公眾號