DEV Community

Sonay Kara
Sonay Kara

Posted on

The performance of your react application is important: Fundamentals useCallback

useClback Hook

We will learn how to cache a function in react. You may need to use useCallback for the performance of your application.

Before you start reading the article, I have a request from you. You can like and share my article. This is very important to me. I am a freelance developer.I can dig your personal website. I can write articles in the field of web development. I can prepare PDF and presentation.

Contact me :
https://www.fiverr.com/zonayovic

Mail : zonaykara@gmail.com

useCallback is a React Hook that lets you cache a function definition between re-renders.



const cachedFunction = useCallback(function, dependencies)


Enter fullscreen mode Exit fullscreen mode
  • Call useCallback at the top level of your component because you can't call it inside loops and conditions. If you have to call it, extract it to a new component and move the state to it.

Image description

Parameters



const cachedFn = useCallback(function, dependencies)


Enter fullscreen mode Exit fullscreen mode

Function : The function value you want to cache. It can take any argument and return any value. React will return your function to you during initial rendering. On subsequent renders, if the dependencies have not changed, React will give you the same functionality again. If the dependencies have changed, it gives you the function you passed during rendering and stores it in case it can be used again later.

Dependencies : all reactive values ​​referenced within the code. Reactive values; It can have props, state, and any variables and functions declared directly in your component body. React will compare each dependency to its previous value using the Object.is comparison algorithm. If the dependencies have changed, the function will return again.

Usage

Skipping re-rendering of components

To optimize, sometimes it's a good idea to cache functions you pass to subcomponents. Let's first examine how to do this, and then look at the situations in which it is useful.

Wrap it in the useCallback Hook to cache a function

Image description

You need to pass two things to useCallback:

  • A function you want to cache.

  • A list of dependencies used inside your function, containing every value in your component.

Conclusion

We learned how to cache a function in react. You may need to use useCallback for the performance of your application. Now you know how to use it

Top comments (0)