Skip to main content

Posts

Showing posts with the label hooks

useCallback hook

Check the code below: usecallback-demo-1-component-renders-unnecessarily - Code You can run the app directly: usecallback-demo-1-component-renders-unnecessarily - App Whenever the button is clicked, the 'increment rendered' message is logged in console. This means, we're rendering the  Increment  component unnecessarily. The Increment component is rendered every time  à  because it depends on  increment  method  à  this method again depends on  count  state  à  so, whenever the  count  state changes, since  count  state is a dependency of  Increment  component, this must be rendered everytime. However, consider the following code where this problem is solved (of course using random number instead of count for demo): usecallback-demo-2-usecallback-prevents-unnecessary-renders - Code Here, we're caching the  increment  method using  useCallback  hook. The  Inc...