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.
We want to compute formatted time and a queue color without recalculating them on every render. useMemo lets us do that by specifying the exact pieces of state that should trigger a recalculation.
Explanation:
- The time string is recomputed only when
gameHourorgameMinutechanges. - By narrowing dependencies, we avoid unnecessary work during unrelated state updates.
Explanation:
- The queue color depends only on
queueLengthandmaxQueue. - When used in styles, having a stable, memoized value reduces repeated calculations and keeps render work small.
These memoized values are then used in the HUD to render the clock, pause/resume button, and the queue bar without recomputing on every tick unless their inputs actually change.
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.
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.
