DEV Community

Cover image for React.js ~State lift down patterns for preventing unnecessary rendering~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

React.js ~State lift down patterns for preventing unnecessary rendering~

React invokes unnecessary rendering as follows;

  • When a state is updated in a component
  • When a parent component is renderd

A component that invokes a heavy rendering

Let's consider aa component that invokes a heavy rendering.
<SuperSlowComponent> is equipped with a while loop that renders a JSX synchronously in 200ms.

import { useState } from "react";

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

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)}
      />
      <SuperSlowComponent />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

The issue is that <SuperSlowComponent> is rendered everytime state is updated by putting values to the input form, and calling setName.

State Lift Down Pattern
This pattern involves a specific state depending on a specific component. By extracting it to another component, the other parts of the component won't be rerendered. This is because the child component keeps the state.

Let's see the paractical codebase.

import { useState } from "react";

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

function Form() {
  const [name, setName] = useState("");

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

export default function App() {
  return (
    <div className="App">
      <Form />
      <SuperSlowComponent />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)