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.

const shopMood = useMemo(() => {
  if (state.resources.satisfaction >= 80) return '🌟 Excellent Service!';
  if (state.resources.satisfaction >= 60) return '😊 Happy Customers';
  if (state.resources.satisfaction >= 40) return '😐 Mixed Reviews';
  return '😟 Customers Unhappy';
}, [state.resources.satisfaction]);

Explanation:

  • The mood is derived solely from satisfaction, so we depend only on that field.
const queueDescription = useMemo(() => {
  if (state.shop.queueLength < 3) return 'Light crowd';
  if (state.shop.queueLength < 8) return 'Steady stream';
  if (state.shop.queueLength < 15) return 'Getting busy!';
  return 'LINE OUT THE DOOR!';
}, [state.shop.queueLength]);

Explanation:

  • The text description tracks queueLength, so this recomputes only when queueLength changes.
const supplyStatus = useMemo(() => {
  const lowSupply =
    state.resources.coffeeBeans < 10 || state.resources.milk < 10;
  if (lowSupply) return '⚠️ Low supplies!';
  return '✅ Well stocked';
}, [state.resources.coffeeBeans, state.resources.milk]);

Explanation:

  • Supply status depends on coffeeBeans and milk counts; 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.memo to 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.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal