Untitled

mail@pastecode.io avatar
unknown
plain_text
13 days ago
884 B
1
Indexable
Never
import React, { useState, useMemo } from 'react';

const ExpensiveComponent = ({ num }) => {
  // Expensive calculation
  const computeFactorial = (n) => {
    console.log('Computing factorial...');
    if (n <= 0) return 1;
    return n * computeFactorial(n - 1);
  };

  // Memoize the result
  const factorial = useMemo(() => computeFactorial(num), [num]);

  return <div>Factorial of {num} is {factorial}</div>;
};

const UseMemoExample = () => {
  const [number, setNumber] = useState(5);
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>useMemo Example</h2>
      <ExpensiveComponent num={number} />
      <button onClick={() => setCount(count + 1)}>Increment Count: {count}</button>
      <button onClick={() => setNumber(number + 1)}>Increment Number: {number}</button>
    </div>
  );
};

export default UseMemoExample;
Leave a Comment