前言
阅读本文章需要对 React hooks 中 useState 和 useEffect 有基础的了解。我的这篇文章内有大致介绍 在 React 项目中全量使用 Hooks。
useCallback
useCallback 的作用
官方文档:
Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.
简单来说就是返回一个函数,只有在依赖项发生变化的时候才会更新(返回一个新的函数)。
useCallback 的应用
在线代码: Code Sandbox
import React, {
useState, useCallback } from 'react';
import Button from './Button';
export default function App() {
const [count1, setCount1] = useState(0);
const [count2, setCount2] = useState(0);
const [count3, setCount3] = useState(0);
const handleClickButton1 = () => {
setCount1(count1 + 1);
};
const handleClickButton2 = useCallback(() => {
setCount2(count2 + 1);
}, [count2]);
return (
<div>
<div>
<Button onClickButton={
handleClickButton1}>Button1</Button>
</div>
<div>
<Button onClickButton={
handleClickButton2}>Button2</Button>
</div>
<div>
<Button
onClickButton={
() => {
setCount3(count3 + 1); }} > Button3 </Button>
</div>
</div>
);
}
// Button.jsx
import React from 'react';
const Button = ({
onClickButton, children }) => {
retur