Blog>
Snippets

React 18's Cleanup with useMemo

Show how useMemo can be used in React 18 to only recompute expensive values when dependencies change and how to properly cleanup the memoized value.
import { useMemo } from 'react';

function ExpensiveComponent({ dependency }) {
  // Use useMemo to create an expensive value
  const expensiveValue = useMemo(() => {
    // Compute expensive value...
    const value = computeExpensiveValue(dependency);

    // Setup a cleanup function
    return () => {
      // Cleanup code here...
      cleanupExpensiveValue(value);
    };
  }, [dependency]);

  return (
    // Render using the expensiveValue
    <div>{expensiveValue}</div>
  );
}
This code block defines a React component that uses the useMemo hook to only recompute an expensive value when the 'dependency' prop changes. It also demonstrates how to setup a cleanup function within useMemo to properly dispose of the memoized value when the component is unmounted or when the dependencies change.