When I started learning React, I came across different hooks like useState , useEffect , and useRef . One hook that I wanted to understand better was useCallback .
At first, I wondered:
Why do we need useCallback ?
What problem does it solve?
When should we use it?
Let's understand it step by step.
1. What is useCallback?
useCallback is a React Hook that memoizes a function.
In simple words, it helps React reuse the same function between renders instead of creating a new function every time.
Syntax:
const memoizedFunction = useCallback ( ( ) => { // Your logic } , [ dependencies ] ) ;
Enter fullscreen mode
Exit fullscreen mode
It takes two arguments:
A function.
A dependency array.
React returns the same function reference as long as its dependencies haven't changed.
2. Why do we need useCallback?
Let's look at a simple example.
import React , { useState } from 'react' ;
function App ( ) { const [ count , setCount ] = useState ( 0 ) ;
const handleClick = ( ) => { console .…