问题描述
从我从 React 文档和网络上的其他材料中了解到,useCallback 用于通过确保将回调的记忆版本传递给子组件来避免重新渲染子组件,因此子组件的引用 props 保持不变.但这一切仅在我在子组件上使用 React.memo 时才有效.没有 React.memo,子组件无论如何都会重新渲染.我的问题是在这种情况下 useCallback 有什么用,即没有将 React.memo 应用于子组件.useCallback 的其他好处是什么?
From what i understood from React documentation and other material across web, useCallback is used to avoid re-rendering of child component by ensuring that memoized version of callback is passed to it, thus referentially props remain same for child component. But all this is valid only if I am using React.memo on child component. Without React.memo, child component would re-render anyways. My question is what use is useCallback in this case i.e. without React.memo applied to child component. What are the other benefits of useCallback?
推荐答案
您可能还需要将函数传递给 useEffect
而无需在每次渲染时更改 useEffect
You might also need to pass a function to useEffect
without changing useEffect
on every render
例如:
import { useCallback, useEffect } from "react";
function useExample() {
function fn() {
console.log("a function");
}
const callback = useCallback(fn, []);
useEffect(() => {
callback();
}, [callback]);
}
使用 useDebounce
的真实示例:
Real-world example with useDebounce
:
这篇关于在没有 React.memo 的情况下使用 useCallback 有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!