ReasonJun

React : useMemo (Hook) 본문

Frontend/React

React : useMemo (Hook)

ReasonJun 2023. 6. 13. 14:46
728x90

useMemo is a hook in React that allows you to memoize the result of a computation. It is used to optimize performance by avoiding unnecessary recalculations of expensive or complex values.

 

When you use useMemo, you provide a function and a dependency array. The function is executed during the rendering phase, and its return value is memoized. The memoized value is then cached and only recalculated if any of the dependencies in the dependency array change.

 

Here's the basic syntax of useMemo:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
  • The first argument is the function that computes the value you want to memoize.
  • The second argument is an array of dependencies. The memoized value will only be recalculated when any of the dependencies change.

Here's an example to demonstrate the usage of useMemo:

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

const ParentComponent = () => {
  const [count, setCount] = useState(0);

  const expensiveValue = useMemo(() => {
    console.log('Expensive value recomputed');
    // Perform expensive computation here
    return count * 2;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <p>Expensive Value: {expensiveValue}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default ParentComponent;

In this example, we have a ParentComponent that renders a count and an expensive value. The expensiveValue is computed using useMemo.

 

The function provided to useMemo performs the expensive computation of multiplying the count by 2. The computed value is memoized and cached. It will only be recomputed when the count dependency changes.

 

By using useMemo, we avoid recomputing the expensive value on every render of the ParentComponent if the count has not changed. This optimization can be particularly useful when dealing with heavy calculations or complex data manipulations within components.

 

It's important to note that useMemo should be used when the computation itself is expensive and the result needs to be cached. If the computation is inexpensive or the result is not going to be reused, using regular function calls or inline expressions would be more appropriate.

728x90
Comments