When I first started with React Hooks I used to initiate each state value with a useState hook, and update it’s value with useEffect on each dependency value change.
This technique will work, but is it possible to improve performance?
So with useMemo we can improve that.
Let’s look on the next example:
We want to calculate the mean of existing segmentsData array —
const meanSpeed = useMemo(() => {
return segmentsData.reduce((accum, current) => {
return accum + current.speed;
}, 0 ) / segmentsData.length;
}, [segmentsData, JSON.stringify(segmentsData)]]);
With useEffect and useState it will look like something like this:
const [meanSpeed, setMeanSpeed] = useState(null);useEffect(() => {
setMeanSpeed(segmentsData.reduce((accum, current) => {
return accum + current.speed;
}, 0 ) / segmentsData.length);
}, [segmentsData, JSON.stringify(segmentsData)]]);
The main diff here is that the useEffect
and setState
will cause extra renders on every change. The useEffect
version is causing twice as much rendering which is bad for performance.
Hope it helped someone there :)
Thanks for reading :)