DEV Community

Sajin Joe J
Sajin Joe J

Posted on

React useCallback – Interview Questions and Answers

Q1. What is useCallback in React?
useCallback is a React Hook that memorizes a function reference. It returns the same function reference between renders until its dependencies change.
Syntax:

const memoizedFunction = useCallback(() => {
  // Function logic
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

Q2. Why do we use useCallback?
We use useCallback to:

  1. Avoid unnecessary function recreation.
  2. Maintain a stable function reference.
  3. Optimize child component rendering when used with React.memo.
  4. Improve performance in certain situations.

Example: useCallback With Dependency

import { useCallback, useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  const showCount = useCallback(() => {
    console.log("Current Count:", count);
  }, [count]);

  return (
    <>
      <h2>Count: {count}</h2>

      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>

      <button onClick={showCount}>
        Show Count
      </button>
    </>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • [count] is the dependency.
  • When count changes, React returns a new function.
  • The function uses the latest count value.

Top comments (0)