useCallback
一句话解释
useCallback 是 Hook 那个返回 memoized version 的回调函数, keeping 相同函数实例跨越渲染.
用大白话说
useCallback caches a function so it keeps the same reference across renders, as long as its dependencies don't change. const fn = useCallback(() => doSomething(a), [a]) returns the same function instance until a changes.
This is useful when you pass callbacks to memoized child components. If the parent creates a new function on every render, the child's React.memo sees a "新" prop and re-renders. Wrapping the callback in useCallback keeps the reference stable, so the memoized child can skip rendering.
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). Use useCallback for functions and useMemo for values — they are the same mechanism under the hood.
示例
const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []);
// The same function reference is passed to the child every render,
// so React.memo on the child can skip re-rendering.
<MemoizedButton onClick={handleClick} />useCallback 返回 stable 函数引用. memoized child sees 相同 onClick prop and skips re-渲染.
相关术语
相关资源
相关课程
- Memoization
学习 useCallback for stable 函数引用.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。