Why Use useCallback Hook In React JS

In this article, we will learn what is used and why to use usecallback hook in react JS.

some times components are rerendered again and again without need and unnecessary renders. it is not the effect of component value but it rerenders the backside again and again and it takes a time to rerender that’s why the application work slow.

The usecallback is to optimize the rendering behavior of your react component.

you can see the example below without usecallback hook to how unnecessary renders.

import React, { useState, useCallback } from 'react'
const funccount = new Set()
export default function Explore() {
  const [count, setCount] = useState(0)
  const [number, setNumber] = useState(0)
  const incrementCounter = () => {
    setCount(count + 1)
  }
  const incrementNumber = () => {
    setNumber(number + 1)
  }
  funccount.add(incrementCounter);
  funccount.add(incrementNumber);
  console.log(funccount.size, "funccount call event size");
  return (
    <div>
      <h2>without Usecallback</h2>
      Count: {count}
      <button onClick={incrementCounter}>
        Increase counter
      </button>
      <button onClick={incrementNumber}>
        increase number
      </button>
      <br />
    </div>
  )
}

In the above code if I click on the increase counter button then it runs event of increment of count but it also runs increment number event which is not needed to render that event.

You can see the output below.

But in the usecallback hook it avoids rendering again and again you can see below example how to avoid rendering of the event

import React, { useState, useCallback } from 'react'
const funccount = new Set()
export default function Explore() {
  const [count, setCount] = useState(0)
  const [number, setNumber] = useState(0)

  const incrementCounterUseCallBack = useCallback(() => {
    setCount(count + 1)
  }, [count])
  const incrementNumberUseCallBack = useCallback(() => {
    setNumber(number + 1)
  }, [number])

  funccount.add(incrementCounterUseCallBack);
  funccount.add(incrementNumberUseCallBack);
  console.log(funccount.size, "funccount call eventsize");
  return (
    <div>
      <h2>with Usecallback</h2>
      Count: {count}
      <button onClick={incrementCounterUseCallBack}>
        Increase counter
      </button>
      <button onClick={incrementNumberUseCallBack}>
        increase number
      </button>
    </div>
  )
}

Here if we click on the increase counter button then it runs only increase counter event not increase the counter number. it means here avoid a not necessary event rendering.

you can see the output below.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories