It is quite evident that React has become widely popular in recent years. To an extent that it has now become the preferred JavaScript library for many players on the internet, including Facebook and WhatsApp. One of the main reasons for such popularity is the introduction of hooks in React version 16.8. React hooks allow developers to tap into React functionality without writing the class components.
Table of Contents
In this article, we will be exploring one specific React hook which is useCallback. We will discuss the most fundamental part of functional programming known as memorization and by the end, you will know exactly how and when to utilize the useCallback hook to improve your code.
Memoization is like making a memo. It is when a complex function stores its output so the next time it can be called with the same input. It is used to skip any complex computations and return the output faster as it is previously calculated. The only downside is that this has a significant effect on memory allocation and the performance of the code. This is where the react useCallback comes in as it is used to alleviate this strain due to extensive memory allocation.
Memoization is a significant feature when it comes to React as it is directly connected with how React renders your components. React uses a Virtual DOM stored in memory to compare the data values and makes the decision on which values are needed to be updated.
By default, if any value in the component changes, the entire component is re-rendered. This makes React “reactive” to the input by the user and allows the screen to update without reloading the page.
Although this makes the application run much faster, it is not necessary to render the component if the changes will not have any effect on the component. This is where memorization comes to the rescue through React useCallback hook.
If you have been working with other React hooks, you might be wondering why another hook such as usememo can be used instead of React useCallback.
The key difference between them is that useMemo returns a memoized value, whereas useCallback returns a memoized function. That means that useMemo can only be used for storing a computed value, while useCallback returns a function that can be called later in the code.
Both of these hooks return a cached version that can be used in later calculations unless one of their dependencies changes.
The code below demonstrates the working of both of the hooks described above:
1. import { useMemo, useCallback } from 'react' 2. const values = [2, 8, 5, 3, 1, 0] // This will always return a sorted array and as the values of the array // will be changed, the result will be recomputed. 3. const memoizedValue = useMemo(() => values.sort(), [values]) // This will provide a function that can be later called. This function will also // return the same result every time unless the array values are changed. 4. const memoizedFunction = useCallback(() => values.sort(), [values])
The code demonstrates a basic example showing the clear difference between the two callbacks:
The memoizedValue will become assigned the sorted array [0, 1, 2, 3, 5, 8]. As long as the array values remain the same, the memoizedValue will not be recomputed unless the array value changes.
memoizedFunction will be a function that will return the sorted array [0, 1, 2, 3, 5, 8].
The most important thing about both of these callbacks is that they become cached and hang around until the dependency array is not changed. This means that every time they are re-rendered without the array being unchanged, the garbage will not be collected.
When React re-renders a component, the functions declared inside the component are also recreated.
The comparison of a function to another function will always result in a false because a function is also an object, it will only equal itself. It means that whenever React re-renders a component, it will always see any declared functions as a function.
See this code snippet below demonstrating how the exactly same functions are considered equal:
1. const func1 = () => console.log('Hello World') 2. const func2 = () => console.log('Hello World') 3. func1 === func2 // false 4. func1 === func1 // true
Although this particular example will not greatly impact the performance as it does not require a lot of processing to compute such functions but this is not the case all the time. To prevent a function to be recognized as a new function, the useCallback function is used.
There are certain cases when using the React useCallback makes much sense, such as:
As mentioned earlier, When React useCallback is used correctly, it can improve the speed of the application by preventing the components from re-rendering if not required.
An appropriate example can be when a component is used that fetches a large amount of data and is responsible for visualizing it like in the form of a graph. Now, Suppose the parent component for that data visualization’s component is re-rendered, but the changed props or state has no effect on that component. In such a case, it is certainly not required to re-render the component and fetch all the data again. Avoiding this re-render and re-fetching of data will not only improve the speed but will also save the bandwidth.
Although the React useCallback can help in improving performance, it also comes with some side effects.
There are a few things to be considered before using useCallback:
As useful as the React useCallback hook is, it is to be noted that there are some very specific use cases where it can be fully utilized. Wrapping every single function with these hooks expecting to improve the speed and performance will result in way more complications than the benefit to the code. If a function is computationally complex, a dependency of another hook or a prop passed to a memoized component are very good indicators that you should use the React useCallback.
This article was an attempt to get a better insight into using the React callback hook the correct way. It is expected that it should have been a great help in understanding some of the most advanced functionalities of React.
Also Read: How React Server Components Work: A Complete Overview
Full Stack Java Developer | Writer | Recruiter, bridging the gap between exceptional talent and opportunities, for some of the biggest Fortune 500 companies.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use