logo

Select Sidearea

Populate the sidearea with useful widgets. It’s simple to add images, categories, latest post, social media icon links, tag clouds, and more.
hello@youremail.com
+1234567890

Follow Us:

Call Now! + (123) 456-7890

 

How to improve application performance with useCallback

How to improve application performance with useCallback

 This is a most useful React hook. The useCallback hook returns a memorized function. This hook has returned the function not the value.

It improves the application performances with cache. It uses the memorization of the function so next call will auto get the response.

The memorized means the system is managing the cache so until we are not getting any change in the function component is not going to re render on each event.

It allows us to isolate the function so it is not going to render on each load. It will only update on dependency changes.

This can improve the application performance.

There is a similar hook useMemo. It is also work as same but useMemo return the value.

import React, { useState, useCallback } from ‘react’;

import Parent from ‘./parent’;

export default function App() {

  const [count, countInc] = useState(1);

  const [counterTwo, countIncForTwo] = useState(2);

  const updateCount = () => {

    console.log(‘Updating my 1 counter’);

    countInc(count + 1);

  };

  const updateCountForTwo = () => {

    console.log(‘Updating my 2 counter’);

    countIncForTwo(counterTwo + 1);

  };

  return (

    <div>

      <Parent

        count={count}

        countInc={updateCount}

        comp=”My Component 1 counter ++”

      />

      <Parent

        count={counterTwo}

        countInc={updateCountForTwo}

        comp=”My Component 2 counter ++”

      />

    </div>

  );

}

import React from ‘react’;

const Parent = ({ count, countInc, comp }) => {

  console.log(comp.slice(0, 12).concat(‘rendered’));

  return (

    <div>

      <span>{count}</span> <br />

      <button onClick={countInc}>{comp}</button>

    </div>

  );

};

export default React.memo(Parent);

Here on each click the Parent component will render. So each click 2 Parent will call.

So with the help of useCallback hook we can change the application performances.

How we can call useCallback?

  const updateCount = useCallback(() => {

    console.log(‘Updating my 1 counter’);

    countInc(count + 1);

  },[]);

 Now the useCallback will prevent the Parent component call on each click. Here useCallback has memorized the function so when we click on the button .It check their previous stage and if there is no changes in previous the it will not going to call Parent component.