Full Stack Development

Expensive? useMemo

by Tomas Trescak t.trescak@westernsydney.edu.au

Conditional Rendering

/

Introduction

      import { render, useState, useEffec, useMemo } from "react";

const calculateFibonacci = (num) => {
  if (num <= 1) return num;
  return calculateFibonacci(num - 1) 
    + calculateFibonacci(num - 2);
};

const App = () => {
  const [num, setNumber] = useState(40);
  const [increment, setIncrement] = useState(0);

  const result = calculateFibonacci(num);


  

  return (
    <div>
      <h1>useMemo Hook Example</h1>
      <p>Result of Expensive Calculation: {result}</p>

      <button onClick={() => setNumber(num + 1)}>
        Change Fibonacci 
      </button> [Fibonacci: {num}]

      {/* Increment unrelated to expensive calculation */}
      <button onClick={() => setIncrement(increment + 1)}>
        Increment Count
      </button> [Count: {increment}]
    </div>
  );
};

render(<App />)