DEV Community

Nikesh Kumar T K
Nikesh Kumar T K

Posted on

React useMemo for optimization

Have you ever used useMemo() hook in your react application ?.

useMemo is an amazing react hook that helps us to optimize our components in react.In this blog, i will show you how we can implement useMemo in our components to make our application more efficent and optimized.

Basically what useMemo do is it catches the data or result of a specific operation.In react, when we changes the state of a variable, the component is rerendered.Each time when the component is rendered, all the operations/calculations are performed again.
This will ultimately affect performance of our app if the operation is an expensive one.
We can avoid this by using useMemo.It takes a callback function and a dependency as arguments.All the operations that have to be performed is wrapped inside callback.Here, the operation is performed only if the state of dependency variable changes even if the component is rerendered.

useMemo implementation

import { useMemo, useState } from "react";

export default function App() {
  const data = [1, 2, 3, 4, 5, 6, 7, 8, 9];

  const [check1, setCheck1] = useState(false);
  const [check2, setCheck2] = useState(false);

  const sum = useMemo(() => {
    console.log("Calculating");
    return data.reduce((acc, data) => acc + data, 0);
  }, [check1]);
  console.log(sum);
  return (
    <div style={{ height: "100vh", display: "grid", placeContent: "center" }}>
      <button 
        onClick={() => setCheck1((p) => !p)}>Button1</button>

      <button 
        onClick={() => setCheck2((p) => !p)}>Button2</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

When the above component is rendered,if you look in the console,it will print "Calculating sum " only when Button1 is clicked.When Button2 is clicked only the sum is printed in the console.This is because i passed the variable check1 as the dependency to the useMemo hook.Hence the sum is calculated only when the state of check1 changes.

Conclusion
Consider using using useMemo in your next react project.It will help you to optimize complex architectures.

Top comments (0)