#16 re-render

easy
react
performance

Imagine an app that has a component that takes a long time to re-render.

export default function App() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <VerySlowComponent />
      <BunchOfStuff />
      <OtherStuffAlsoComplicated />
    </>
  );
}

export default App;

Now you are required to add a Button that opens a dialog. For that you added button and dialog and a state to manage the dialog.

export default function App() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <Button onClick={() => setIsOpen(true)}>Open dialog</Button>
      {isOpen ? <ModalDialog onClose={() => setIsOpen(false)} /> : null}
      <VerySlowComponent />
      <BunchOfStuff />
      <OtherStuffAlsoComplicated />
    </>
  );
}

But the problem is with the above code is that because of slow component re-rendering, the dialog takes more than 1 second to open. How can we optimize this?