Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - useMemo without dependencies array vs empty array

What is the difference between doing

const value = useMemo(() => {
     ...
});

and

const value = useMemo(() => {
     ...
}, []);

?

like image 297
Raul Avatar asked Jul 24 '21 21:07

Raul


People also ask

Why you should not use 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.

What happens if we don't pass dependency array in useEffect?

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.

What if dependency array is empty in useEffect?

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.

When should we not use useCallback and useMemo?

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.


1 Answers

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>
like image 174
CertainPerformance Avatar answered Oct 16 '22 17:10

CertainPerformance