DEV Community

Cover image for React UseCallBack Hook
Narasimma Radhakrishnan
Narasimma Radhakrishnan

Posted on

React UseCallBack Hook

whenever a React component re-renders, the functions inside that component are normally recreated. To avoid unnecessary function reference changes, we can use useCallback.
useCallback is a React Hook that memoizes a function and returns the same function reference until its dependencies change.

import React, { useCallback, useState } from 'react'

function UseCallbackhook() {
    const[count,setCount] = useState(0);
    const[msg,setMsg] = useState("");
    function increase(){
        setCount(count+1);
    }
    // function fncallback(){
    //     console.log("hello world");
    // }
    const fncallback = useCallback(()=>{
        setMsg("hello world");
        console.log("hello world")
    },[]);
  return (
    <div>
      <h1>count : {count}</h1>
      <h1>message :{msg} </h1>
      <button onClick={increase}>+</button>
      <button onClick={fncallback}> show message</button>
    </div>
  )
}

export default UseCallbackhook

Enter fullscreen mode Exit fullscreen mode

How does it work?
Initially, the component renders.
useCallback remembers the showMessage function reference.
When we click Increase, the count changes.
React re-renders the component.
Since the dependency array is empty, React returns the same function reference.

Advantages of useCallback

Helps avoid unnecessary function reference changes.
Useful when passing functions to memoized child components.
Helps optimize component rendering in suitable situations.
Useful when a function is a dependency of another Hook.

Top comments (0)