React hooks deep dive - useCallback, useMemo, and memo
In the ever-evolving world of React, mastering hooks is essential for writing efficient and optimized code. But wait, what exactly are hooks? In the simplest terms, hooks are like real-life hooks that help us attach or "hook" into certain things within our React components.
In context of React, Hooks are essentially functions that keep some data consistent across these re-renders.
When we talk about React components, they re-render whenever their state or props change.Re-rendering is crucial for good user experience and interactivity. But why does this happen? It often happens because JavaScript treats every function as a new object, causing reference changes even when the function logic remains the same.
The next section is crucial, pay attention
Understanding Primitive Values vs. Objects in JavaScript
In JavaScript, we have two categories of data: primitive values (like numbers and strings) and objects (including functions, arrays, classes, etc.). Primitive values are compared by their value, while objects are compared by their reference or memory address.
When a React component re-renders, it compares the previous and current props to determine if it should update the component. For primitive values, this comparison is straightforward because they are compared by value. For example, if a number was 5 in the previous render and is still 5 in the current render, React recognizes no change and doesn't re-render the component.
However, functions are objects in JavaScript and are compared by reference. Each time a component re-renders, the function gets a new memory address, even if the function logic remains the same. As a result, React considers it a new function and will re-render the child component that receives this function as a prop, which can degrade performance.
Introducing useCallback, useMemo, and memo
useCallback is a hook that helps memoize a function so that it doesn't get re-created on every re-render until its dependencies change. This is crucial for optimizing performance, especially in components that rely heavily on callback functions passed down as props.
Similarly, useMemo is used to memoize a value or object. Imagine you have an e-commerce application, and on the frontend, you receive a large object of data. From this, you calculate the average of likes to show the rating. Since the value is calculated from the object, each re-render assigns it a new memory address, which we want to avoid. Just like useCallback
, we use useMemo
to memoize that value.
And when we need to memoize an entire component, we wrap the component in memo. Since every component is essentially a function that returns JSX, memoizing it can prevent unnecessary re-renders.
Practical Usage
Now, let's see how to use these hooks.
Using useCallback
is straightforward. It takes two arguments: the function to memoize and an array of dependencies. The function will only be re-created if one of the dependencies changes.
Here's an example:
import React, { useCallback, useMemo, memo } from "react";
// useCallback example
const ShowCount = () => {
const [count, setCount] = React.useState(0);
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
return <CountButton onIncrement={increment} />;
};
// useMemo example
const calculateRating = (data) => {
let totalLikes = 0;
data.forEach((item) => {
totalLikes += item.likes;
});
return totalLikes / data.length;
};
const RatingComponent = ({ data }) => {
const rating = useMemo(() => calculateRating(data), [data]);
return <div>Average Rating: {rating}</div>;
};
// memo example
const CountButton = memo(({ onIncrement }) => {
return <button onClick={onIncrement}>Increment</button>;
});
By using useCallback
, useMemo
, and memo
, you can significantly improve the performance of your React applications, avoiding unnecessary re-renders and ensuring smoother user experiences.
I hope this helped you get a better Understanding of these hooks.At the end these are all JavaScript functions.
Happy coding!.
Top comments (0)