Q1. What is the useCallback hook?
This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary re-renders.
useCallback returns a memoized version of a callback function that only changes if one of the dependencies has changed.This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary re-renders.
Q2. How do you use useCallback?
Example:
Without
const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b]);
The function is recreated only if a or b change.Without
useCallback, a new function is created on every render.Q3. When is useCallback necessary?
It's necessary when you pass callbacks to child components that are memoized with
If the callback changes on every render, the child will re-render unnecessarily.
React.memo.If the callback changes on every render, the child will re-render unnecessarily.
useCallback stabilizes the function reference.Q4. What is the difference between useCallback and useMemo?
It memoizes the function itself, while
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).It memoizes the function itself, while
useMemo memoizes the result of calling a function.Q5. Can overusing useCallback hurt performance?
Yes,
It's best to use it only when needed, such as when you have expensive child components or custom hooks that rely on stable references.
useCallback itself has overhead.It's best to use it only when needed, such as when you have expensive child components or custom hooks that rely on stable references.
