React
Top 10 React.js useCallback() Interview Question
Interview questions on callback memoization, dependency arrays, and React rendering performance.
-
What is the
useCallbackhook in React?It memoizes a callback function, preventing unnecessary re-creations on re-renders unless dependencies change.
-
What is the syntax of
useCallback?const memoizedCallback = useCallback(callback, [dependencies]); -
Why would you use
useCallback?To optimize performance by memoizing functions passed as props to prevent unnecessary re-renders in child components.
-
How does
useCallbackdiffer fromuseMemo?useCallbackmemoizes functions, whileuseMemomemoizes computed values. -
When should you avoid using
useCallback?Avoid it for simple functions or when memoization doesn't provide significant performance benefits.
-
What happens if you omit the dependency array in
useCallback?The callback is re-created on every render, negating the memoization benefit.
-
Can
useCallbackimprove performance in all cases?No, it only helps when preventing unnecessary re-renders in components that rely on stable function references.
-
How does
useCallbackwork with React's dependency array?It re-creates the memoized function only when one or more dependencies change.
-
Can
useCallbackbe used with inline functions?Yes, but it’s typically used to memoize functions defined inline to maintain reference stability.
-
What is a common use case for
useCallback?Passing a stable callback to a child component or a hook like
useEffectto avoid unnecessary re-renders or effects.