What is the difference between doing
const value = useMemo(() => {
...
});
and
const value = useMemo(() => {
...
}, []);
?
useMemo itself requires memory so if we are trying to over-optimize by memoizing every function, it might slow the application down. We should also not use useMemo when the function returns a primitive value, such as a boolean or a string.
Empty dependency array So what happens when the dependency array is empty? It simply means that the hook will only trigger once when the component is first rendered. So for example, for useEffect it means the callback will run once at the beginning of the lifecycle of the component and never again.
If it's empty ( [] ), the effect runs once, after the initial render. It must — or as we'll see later, should — contain the list of values used in the effect. The effect runs after any of these values changes (and after the initial render). The array of dependencies is not passed as argument to the effect function.
UseCallback is used to optimize the rendering behavior of your React function components, while useMemo is used to memoize expensive functions to avoid having to call them on every render. As a standard construction of hooks, those two solutions are not so different.
Using useMemo()
without dependencies array will calculate the value
on every render.
If no array is provided, a new value will be computed on every render.
It'll be equivalent to
const value = ...
Using useMemo()
with an empty dependencies array will calculate the value
only once, on mount.
Demo:
const App = () => {
const value1 = React.useMemo(() => {
console.log('calculating value1');
});
const value2 = React.useMemo(() => {
console.log('calculating value2');
}, []);
const [counter, setCounter] = React.useState(0);
return (
<button onClick={() => setCounter(counter + 1)}>{counter}</button>
);
};
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With