Nearby lessons
24 of 44🪝 ReactJS – useCallback Hook
📌 What is useCallback?
What is useCallback in React?
The useCallback hook returns a memoized function.
It is useful when passing callbacks to child components that rely on reference equality
to prevent unnecessary re-renders.
The useCallback and useMemo hooks are similar:
useMemo→ returns a memoized value.useCallback→ returns a memoized function.
📌 Syntax of useCallback
const memoizedFn = useCallback(() => {
// logic here
}, [dependencies]);
- Callback Function: The function you want to memoize.
- Dependencies: The function is re-created only when dependencies change.
⚙️ Without useCallback
In this example, the Learning function is recreated every time the parent
App re-renders. This causes the child component to re-render unnecessarily
even if Learning does not change.
import React, { useState } from 'react'; import ChildA from './ChildA'; function App() { const [add, setAdd] = useState(0); const [count, setCount] = useState(0); const Learning = () => { // some operation }; return ( <> <h1>Learning useCallback</h1> <ChildA Learning={Learning} count={count} /> <h1>{add}</h1> <button onClick={() => setAdd(add + 1)}>Addition</button> <h1>{count}</h1> <button onClick={() => setCount(count + 2)}>Count</button> </> ); } export default App;
✅ With useCallback
Here, useCallback ensures that Learning function is
memoized. It will only re-create if dependencies change, preventing
unnecessary child re-renders.
import React, { useState, useCallback } from 'react'; import ChildA from './ChildA'; function App() { const [add, setAdd] = useState(0); const [count, setCount] = useState(0); const Learning = useCallback(() => { // some operation }, []); return ( <> <h1>Learning useCallback</h1> <ChildA Learning={Learning} count={count} /> <h1>{add}</h1> <button onClick={() => setAdd(add + 1)}>Addition</button> <h1>{count}</h1> <button onClick={() => setCount(count + 2)}>Count</button> </> ); } export default App;
🧮 Execution Flow of useCallback
- React renders the parent component (
App). - The
Learningfunction is created. - If
useCallbackis used, the same function reference is reused unless dependencies change. - The child component (
ChildA) receives props. - Because of
React.memo,ChildAonly re-renders if props actually change.