DEV Community

Cover image for useCallback the Hook
sonu sharma
sonu sharma

Posted on

1

useCallback the Hook

My 2 cents on useCallback React hook.

useCallback hook memoizes the callback function passed to it as argument. In simple words it will not create another instance of same function until the value in second argument passed in the useCallback as array of dependency changes.

Simple way to test whether the passed callback function has changed is by the set test. When ever the useCallback hook is called, add the function returned to the set and check the size of the set. if the size has increased that means a new function instance has been created.

When you call useCallback hook with only one argument, that is without dependencies it does nothing.

I think i have got the basics right. But i am not able to solve un necessary re-rendering of <ShowProducts/> component.

First of all why it is a issue, it is a problem since i think ShowProducts re-rendering is unnecessary because looking at the props i am passing to this components are arrayOfProducts and a call back function to update how many times a item has been clicked / selected updateSelectedCount.

I understand that every time selectedCount changes a new instance of updateSelectedCount is generated so the ShowProducts component re-renders. But my question is why it should bother about the updateSelectedCount being changed.

My question is how i can stop re-rendering <ShowProducts/> keeping all the functionality intact.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay