React useMemo

Created By: chatGPT

In React, the useMemo hook is used to optimize performance by memoizing the result of a calculation so that it only re-computes when its dependencies change. This is especially useful for expensive calculations that do not need to run on every render.
// Example of useMemo in a functional component
import React, { useMemo, useState } from 'react';

const ExpensiveComponent = () => {
    const [count, setCount] = useState(0);

    // A function that simulates an expensive calculation
    const calculateFactorial = (n) => {
        console.log('Calculating factorial...');
        return n <= 0 ? 1 : n * calculateFactorial(n - 1);
    };

    // Use useMemo to memoize the result of the calculation
    const factorial = useMemo(() => calculateFactorial(count), [count]);

    return (
        <div>
            <h1>Factorial of {count}: {factorial}</h1>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
};

export default ExpensiveComponent;
In this example, we create a functional component called ExpensiveComponent. It includes a state variable count that increments when a button is clicked. The calculateFactorial function is defined to compute the factorial of the current count, which is an expensive operation. Instead of recalculating the factorial on every render, we use useMemo to calculate it only when count changes.
// Using the component in an App
import React from 'react';
import ExpensiveComponent from './ExpensiveComponent';

const App = () => {
    return (
        <div>
            <h1>React useMemo Example</h1>
            <ExpensiveComponent />
        </div>
    );
};

export default App;
With this setup, the console will only log 'Calculating factorial...' when the count changes, demonstrating that useMemo prevents unnecessary calculations. This results in a more performant application, especially as the complexity of calculations increases.
// Custom hooks can also utilize useMemo
const useEnhancedMemo = (value, dependencies) => {
    return useMemo(() => value, dependencies);
};
Introduction And SetupComponentsPropsStateLifecycle MethodsHooksContext APIJsx SyntaxVirtual DomEvent HandlingFormsRoutingPerformance OptimizationError BoundariesHigher Order ComponentsRender PropsPortalsFragmentsRefsControlled ComponentsUncontrolled ComponentsMemoizationSuspenseLazy LoadingProp TypesDefault PropsConditional RenderingList And KeysAccessibility (a11y)State ManagementTestingCustom HooksUseEffectUseStateUseContextUseReducerUseMemoUseCallbackUseRefUseLayoutEffectUseImperativeHandleUseDebugValueAutomatic BatchingSuspense For Data FetchingStrict ModeForward RefsCreateContextLazyUseTransitionUseDeferredValueUseId