DEV Community

Cover image for React.js ~useEffect memoization pattern for preventing unnecessary rendering~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~useEffect memoization pattern for preventing unnecessary rendering~

This pattern is memoization with React.memo. This is known as optimization among React developer.

React.memo reuses a memoiszed component without rerendering if it is necessary in comparison between current Props and previous one.

In the demo below, even though the name state changes and the <App /> component re-renders, the props passed to the <SuperSlowComponent /> component do not change, so <SuperSlowComponent /> does not re-render.

import { memo, useState } from "react";

function SuperSlowComponent() {
  const now = performance.now();
  while (performance.now() - now < 200) {}
  return (
    <>
      <div>Super slow component</div>
    </>
  );
}

const MemoSupserSlowComponent = memo(SuperSlowComponent);

export default function App() {
  const [name, setName] = useState("");

  return (
    <div className="app">
      <label htmlFor="name">Name</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <MemoSupserSlowComponent />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)