Q1. How does useCallback improve performance?
This prevents child components that rely on reference equality from re-rendering unnecessarily.
useCallback returns a memoized version of a function, so the same function reference is used across renders unless dependencies change.This prevents child components that rely on reference equality from re-rendering unnecessarily.
Q2. When should you use useCallback?
Use it when passing callbacks to optimized child components (like those wrapped in
Also useful in hooks dependencies to avoid infinite loops.
React.memo).Also useful in hooks dependencies to avoid infinite loops.
Q3. Can overusing useCallback be harmful?
Yes, it adds overhead and complexity.
Only use it when you have measured or identified a performance issue.
Most of the time, creating new functions is cheap.
Only use it when you have measured or identified a performance issue.
Most of the time, creating new functions is cheap.
Q4. What is the difference between useCallback and useMemo?
They are both used for optimization but for different purposes.
useCallback returns a memoized function; useMemo returns a memoized value.They are both used for optimization but for different purposes.
Q5. How do you use useCallback with dependencies?
Pass an array of dependencies.
The function will be recreated only when a dependency changes.
Example:
The function will be recreated only when a dependency changes.
Example:
const handleClick = useCallback(() => { doSomething(id); }, [id]);