React useCallback

Created By: chatGPT

useCallback is a React Hook that helps you optimize your component's performance by memoizing a function. It returns a memoized version of the callback function that only changes if one of the dependencies has changed. This is especially useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
import React, { useState, useCallback } from 'react';

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

    const increment = useCallback(() => {
        setCount(c => c + 1);
    }, []);

    return (
        <div>
            <h1>{count}</h1>
            <button onClick={increment}>Increment</button>
        </div>
    );
};
In this example, the increment function is memoized using useCallback. It will always be the same instance unless the dependencies change. This allows components like React.memo to prevent unnecessary re-renders.
const ChildComponent = React.memo(({ onIncrement }) => {
    console.log('Child Component Rendered');

    return <button onClick={onIncrement}>Increment from Child</button>;
});
To use the ChildComponent, you can render it inside MyComponent and pass the increment function as a prop. This ensures that ChildComponent only re-renders when the increment function changes due to dependency updates.
const MyComponent = () => {
    const [count, setCount] = useState(0);

    const increment = useCallback(() => {
        setCount(c => c + 1);
    }, []);

    return (
        <div>
            <h1>{count}</h1>
            <ChildComponent onIncrement={increment} />
        </div>
    );
};
useCallback can also accept dependencies to update the memoized function when they change. This can help you manage more complex logic or when interacting with state or props that change over time.
const MyComponent = ({ initialCount }) => {
    const [count, setCount] = useState(initialCount);

    const increment = useCallback(() => {
        setCount(c => c + 1);
    }, [initialCount]);

    return (
        <div>
            <h1>{count}</h1>
            <button onClick={increment}>Increment</button>
        </div>
    );
};
Remember that using useCallback might add overhead to your component. It should be used only when necessary, particularly when dealing with child components that are optimized with React.memo.
const MyOtherComponent = () => {
    // Without useCallback
    const [count, setCount] = useState(0);

    const handleIncrement = () => {
        setCount(c => c + 1);
    };

    return <button onClick={handleIncrement}>Increment</button>;
};
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