frontend-challenges
frontend-challenges copied to clipboard
re-render 2
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;
#166 - Pull Request updated.