useCallback
useCallback用来保存上次创建的函数实例,用来缓存函数,要配合memo一起使用
import React, {memo, useCallback, useState} from 'react';
import {Button, Input, List} from "antd";
const defaultNumbers = Array.from({length:1000}).map((_,index) => index +1);
function Index() {
const [keywords, setKeywords] = useState<string>('');
// 启用useCallback
const handleClick = useCallback(
(index: number) => {
console.log(`点击了第${index}列`)
},[]
)
// 禁用useCallback
// const handleClick = (index: number) => {
// console.log(`点击了第${index}列`)
// }
return (
<div>
<Input placeholder="请输入关键词" onChange={(e) => setKeywords(e.target.value)} style={{ width: 200 }} />
当前查询关键词为:{keywords}
<List
size="small"
bordered
dataSource={defaultNumbers}
renderItem={(item) => <Children index={item} onClick={handleClick}/>}
/>
</div>
);
}
interface Options {
index: number
onClick: (index: number) => void
}
const Children: React.FC<Options> = memo(({index, onClick}) => {
console.log('Children重新渲染了')
return (
<div>
<Button type={'primary'} onClick={() => onClick(1)}>第{index}项</Button>
</div>
)
})
export default Index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 何时使用依赖项
如果函数体内有内容依赖于外部某个state属性,此时useCallback应增加依赖项,否则不需要增加依赖项
const [name, setName] = useState('刘杰');
const Person = useCallback(() => {
return <div>{name}</div>
}, [name]);
1
2
3
4
5
2
3
4
5
# 应用场景
- 包装在React.memo()的子组件,props中存在回调函数时(如:onClick),该函数(handleClick)应该用useCallback进行缓存
- 当hooks依赖于该回调函数时(如
useEffect(...,[callback])
),应该使用useCallback进行缓存
编辑 (opens new window)
上次更新: 2023/02/16