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]); Q2. Why do we use useCallback?
We use useCallback to:
- Avoid unnecessary function recreation.
- Maintain a stable function reference.
- Optimize child component rendering when used with React.memo.
- 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; Explanation:
- [count] is the dependency.
- When count changes, React returns a new function.
- The function uses the latest count value.
