Q1. What is the useCallback hook?
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: 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 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?
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, 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.
