DEV Community

Deva I
Deva I

Posted on

useMemo Hook in React

useMemo :

The useMemo is designed to optimize performance by caching (memoizing) the result of a calculation between component re-renders.

The useMemo Hook only runs when one of its dependencies update.

syntax :

const Value = useMemo(() => calculateValue(a, b), [a, b]);
Enter fullscreen mode Exit fullscreen mode

useMemo have two arguments one is Calculate Function and another one is dependency array.

Example Code :


function App() {
  const [count, setCount] = useState(0)
  const [arr, setArr] = useState([1, 2, 3, 4])

  const showMax = useMemo(() => {
    console.log("Component re-rendered");
    return Math.max(...arr)
  },
    [arr]);

  const addNew = () => {
    setArr([count + 5]);
  }
  return (
    <div>
      <h2>Count = {count}</h2>
      <button onClick={() => setCount(count + 1)}>count</button>
      <button onClick={addNew}>Addnew</button>
      <p>Max value = {showMax}</p>

    </div>

  )
}

export default App

Enter fullscreen mode Exit fullscreen mode

Output :

Top comments (0)