Dev.to WebDev 🛠 Dev 👁 0

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 pr

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>
  );
}

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.