Optimizing Performance with useMemo and useCallback
As a production-ready engineer, it's important to be conscious of performance optimization techniques in your JavaScript and React code. One common scenario where performance optimization is key is when dealing with expensive computations or functions that are called frequently.
React provides built-in hooks useMemo
and useCallback
that can help optimize performance by memoizing values and functions.
useMemo
The useMemo
hook is used to memoize the result of a function call and avoids re-computing it every time a component renders.
The basic syntax of useMemo
is:
1const memoizedValue = useMemo(() => {
2 // expensive computation
3 return someValue;
4}, [dependencies]);
The first argument to useMemo
is a callback function that performs the expensive computation and returns a value. The second argument is an array of dependencies (optional) which instructs React to recompute the memoized value whenever any of the dependencies change.
Memoization helps to avoid unnecessary calculations and improves performance, especially when dealing with computationally expensive operations.
Here's an example of memoizing the Fibonacci and factorial functions using useMemo
:
xxxxxxxxxx
// Example 1
const fibonacci = (n) => {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
};
console.log(fibonacci(10));
// Example 2
const factorial = (n) => {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
};
console.log(factorial(5));