useCallback跟useMemo比较类似,但它返回的是缓存的函数。
函数式组件中,使用useCallback对函数进行缓存(被外层函数包裹,相当于闭包),组件再次更新时(函数重新执行)会根据依赖是否变化决定选用缓存函数还是新函数
父组件
import { useState, useCallback, Fragment } from 'react';
import Child from './Child'
const index = () =>
{
const [count, setCount] = useState(1);
const [content, setContent] = useState('Lee');
// 修改input的 `content`值
const intChang = (event) =>
{
const { target } = event
setContent(target.value)
}
const callback = useCallback(() =>
{
console.log(count, content, 'callback');
return count;
}, []);
return (
<Fragment>
<h4>父组件的值:{count}</h4>
<Child callback={callback} />
<div>
<button onClick={() => setCount(count + 1)}>+</button>
<input value={content} onChange={intChang} />
</div>
</Fragment>
);
};
export default index
子组件
import { useState, useEffect } from 'react';
const index = ({ callback }) =>
{
// console.log(callback, 'callback2222222222');
// const [count, setCount] = useState(_ => callback());
// useEffect(() =>
// {
// setCount(callback());
// }, [callback]);
// console.log(321, '子组件');
const count = callback()
return (
<div>
{count}
</div>
);
};
export default index
无依赖的情况