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(someNumber: number): number | null {
const [result, setResult] = useState<number | null>(null);
useEffect(() => {
setResult(expensiveCalculation(someNumber));
}, [someNumber]);
return result;
}
useMemo
import { expensiveCalculation } from "foo";
function useCalculateWithMemo(someNumber: number): number {
return useMemo(() => {
return expensiveCalculation(someNumber);
}, [someNumber]);
};
Both calculate the result each time their parameter someNumber
changes, where is the memoization of useMemo
kicking in?
null
on the first render, while the second won't? – Anadem