The useMemo hook allows you to memoize a value so that it’s only re-computed when its dependencies change. This can help improve performance by preventing unnecessary re-computations.
Here’s an example of how to use useMemo to memoize a calculated value:
import React, { useState, useMemo } from 'react'; function ExpensiveCalculation({ a, b }) { const result = useMemo(() => { console.log('Calculating...'); return a * b; }, [a, b]); return <p>Result: {result}</p>; }
In this example, we define an ExpensiveCalculation component that takes two props, a and b. We use the useMemo hook to memoize the result of the calculation so that it’s only re-computed when a or b changes.