top of page
Logo der Online Agentur mdwp

Memoization Hooks

In React JS, memoization is a technique used to optimize performance by storing the results of expensive function calls, and reusing them when the same inputs occur again.

One of the Hooks provided by React for memoization is "useMemo". The "useMemo" hook is used to memorize complex computations between renderings. When the dependencies of this hook change, it recalculates the cached value and stores it for future reference. If the dependencies haven't changed in the next render, it will use the previously cached value.

Here is a simple piece of code to illustrate how useMemo works:

```
import React, { useState, useMemo } from 'react';

function ExampleComponent() {
const [num, setNum] = useState(1);
const [inc, setInc] = useState(0);

const expensiveComputation = useMemo(() => {
return performExpensiveComputation(num);
}, [num]);

return (
<>
<p>{`Memoized Value: ${expensiveComputation}`}</p>
<button onClick={() => setInc(inc + 1)}>
Increment
</button>
<button onClick={() => setNum(prevNum => prevNum * 2)}>
Double the num
</button>
</>
);
}

function performExpensiveComputation(num) {
console.log('Perform complex computation');
return num * num;
}
```
In this code block, useMemo is memorizing the result of `performExpensiveComputation(num)` until the `num` value changes, preventing unnecessary calls to that function and thus improving performance.

A similar hook is "useCallback", used to memoize functions instead of computed values.

These hooks become particularly important when dealing with components rendering a high volume of data, or with functions that are computationally expensive. They can significantly increase performance by reducing the number of re-renders and computations necessary.

Remember that overusing these hooks can also lead to problems - the resources necessary to store the memoized values can outweigh the performance benefits of memoization. You should consider using them carefully and predominantly when dealing with expensive computations or a significant number of re-renders.

bottom of page