Are there any benefits in using useMemo
(e.g. for an intensive function call) instead of using a combination of useEffect
and useState
?
Here are two custom hooks that work exactly the same on first sight, besides useMemo
's return value being null
on the first render:
useEffect & useState
import { expensiveCalculation } from "foo";
function useCalculate(numberInput: number): number {
const [result, setResult] = useState<number>(null);
useEffect(() => {
setResult(expensiveCalculation(numberInput));
}, [numberInput]);
return result;
}
useMemo
import { expensiveCalculation } from "foo";
function useCalculateWithMemo(numberInput: number): number {
return useMemo(() => {
return expensiveCalculation(numberInput);
}, [numberInput]);
};
Both calculate the result each time their parameter someNumber
changes, where is the memoization of useMemo
kicking in?