Created
November 8, 2023 13:22
-
-
Save joaomantovani/a5d28c04dad023f999df236490dd41cc to your computer and use it in GitHub Desktop.
A react example to show how to use useMemo to resolve fibonacci problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useMemo, useState } from "react"; | |
import "./App.css"; // Supondo que os estilos estejam definidos em App.css | |
// Função computacionalmente cara | |
const calculaFibonacci = (n: number): number => { | |
if (n <= 1) { | |
return n; | |
} | |
return calculaFibonacci(n - 1) + calculaFibonacci(n - 2); | |
}; | |
const App = () => { | |
const [num, setNum] = useState(10); | |
const [isGreen, setIsGreen] = useState(false); | |
// Cálculo caro a cada renderização | |
const fib = useMemo(() => { | |
if (num <= 1) { | |
return num; | |
} | |
return calculaFibonacci(num - 1) + calculaFibonacci(num - 2); | |
}, [num]); | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<h3 | |
onClick={() => setIsGreen(!isGreen)} | |
style={{ color: isGreen ? "green" : "white" }} | |
> | |
Fibonacci de {num} é {fib} | |
</h3> | |
<br /> | |
<br /> | |
<br /> | |
<button onClick={() => setNum(num + 1)}>Incrementar</button> | |
</header> | |
</div> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment