jsartisan / frontend-challenges

FrontendChallenges is a collection of frontend interview questions and answers. It is designed to help you prepare for frontend interviews. It's free and open source.
https://frontend-challenges.com
45 stars 5 forks source link

re-render 2 #165

Open jsartisan opened 2 months ago

jsartisan commented 2 months ago

Info

difficulty: easy
title: re-render 2
type: question
template: react
tags: react, performance

Question

Imagine a site that has a slow component.

const App = () => <SlowComponent />;

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.

const App = () => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <SlowComponent />
      <button onClick={() => setIsDialogOpen(true)}>Open Dialog</button>
      {isOpen && (
        <dialog open={isOpen}>
          <button onClick={() => setIsOpen(false)}>Close Dialog</button>
        </dialog>
      )}
    </>
  );
};

export default App;

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?

Template

App.jsx

import { useState } from "react";
import SlowComponent from "./SlowComponent";

const App = () => {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <SlowComponent />
      <button onClick={() => setIsOpen(true)}>Open Dialog</button>
      {isOpen && (
        <dialog open={isOpen}>
          <button onClick={() => setIsOpen(false)}>Close Dialog</button>
        </dialog>
      )}
    </>
  );
};

export default App;

SlowComponent.jsx

import React from "react";

const SlowComponent = () => {
   const fibonacci = (n) => {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
  };

  const number = 35; 
  const result = fibonacci(number);

  return (
    <div>
      <h1>Fibonacci of {number} is: {result}</h1>
    </div>
  );
};

export default SlowComponent;
github-actions[bot] commented 2 months ago

166 - Pull Request updated.