Optimizing Derived State
Optimizing Derived State with useMemo
In the last lesson, you stabilized renders with React.memo so that static UI and event handlers stayed quiet during the 1-second game loop. As a quick reminder, that cut down on re-renders triggered by prop changes. In this lesson, you will go one step further: use useMemo to cache expensive derived values so they only recompute when their inputs change. This keeps the UI responsive even while the TICK action runs every second.
Memoizing derived values in GameHUD
Memoizing derived values in ShopView
ShopView also presents data that is derived from state. Memoizing these values keeps the component fast and predictable as the game runs.
Explanation:
- The mood is derived solely from
satisfaction, so we depend only on that field.
Explanation:
- The text description tracks
queueLength, so this recomputes only whenqueueLengthchanges.
Explanation:
- Supply status depends on
coffeeBeansandmilkcounts; those are the only dependencies. - Keeping the dependency list tight ensures minimal recalculation during the game loop.
Using useMemo across these derived values makes ShopView responsive and avoids recomputing descriptions when irrelevant parts of state change.
Summary and next steps
You just optimized derived state with useMemo by:
- Computing values only when their specific inputs change.
- Keeping dependency arrays tight so the game loop does not trigger extra work.
- Pairing well with the previous lesson’s
React.memoto minimize heavy calculations.
You will now get a chance to apply these patterns yourself. Let’s jump into the practice section and make the HUD and shop feel even snappier.
