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