Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Routing and Application Architecture
Stage 5: Specialization (pick ONE)

Project

Expense Tracker UI

Start after Part 10

Stage 2

Goal: Build a real, clickable expense tracker - add, edit, delete, and clear expenses through one useReducer-driven list, with a theme and currency-display setting shared through context, and the list itself persisted to localStorage through a debounced custom hook. Time: ~6 hours · Uses: Parts 5-10 (forms, effects, custom hooks, useContext, useReducer) - no network calls anywhere

Project brief

This is deliberately the same idea as the Python course's CLI Expense tracker - rent, groceries, petrol, electricity, food - rebuilt as a client-side UI instead of a terminal. It even starts from the exact same seven sample expenses. Where the CLI version typed add 250 food --note "Dinner delivery" and read a table back, this version types into a form and sees the list update immediately, with a running total and a category breakdown that never go stale - and, unlike the CLI's --file flag, it remembers your data by itself between visits, in the browser.

Add: ₹250, food, "Dinner delivery"   → appears in the list; Total: ₹36,995.50
Switch to compact amounts            → Total: ₹36,995.50 becomes Total: ₹37.0k
Switch to dark theme                 → the whole app's background/text swap, instantly
Refresh the page                     → every expense is still there (localStorage)

Files

File What it is
README.md This brief and the step-by-step build guide
data.js The fixed CATEGORIES list and the seven seed expenses (same data as the Python CLI project)
expensesReducer.js The pure reducer (add/edit/delete/clear) and the lazy-init loader, both plain functions
ThemeContext.jsx ThemeProvider/useTheme (theme + currency display) and the formatRupees helper
usePersistedExpenses.js A custom hook: a debounced useEffect that saves the expense list to localStorage, with a real cleanup function
ExpenseTracker.jsx Complete reference implementation (try building your own first!)
expensesReducer.test.jsx The reducer and the lazy-init loader, tested directly - no component, no render
ThemeContext.test.jsx The context/custom-hook pair, including the outside-provider safety throw
usePersistedExpenses.test.jsx The debounce-and-cancel behavior, with fake timers
ExpenseTracker.test.jsx The whole app wired together - every verified behavior below is actually run

How to run

This project reuses the one repo-level harness (Node 22, npm 11, Vitest + Testing Library - see ../../TOOLING.md) - no separate install, no separate package.json. From the repo root:

npx vitest run stage-2-intermediate/project-expense-tracker-ui

To actually see it render, add <ExpenseTracker /> to harness/src/App.jsx temporarily (import it from this folder) and run npm run dev - then remove the import again once you are done, so the harness keeps showing whichever part it is currently wired for.

Features

Feature What it does
Add an expense A form (amount, category, note, date) validates the amount live and adds a new expense with the next free id
Edit an expense Each row has an "Edit" button that turns it into an inline form for amount/note, with "Save"/"Cancel"
Delete an expense Each row has a "Delete" button that removes exactly that one expense
Clear all One button empties the whole list in one dispatch; disabled once the list is already empty
Running total A derived (never separately stored) sum of every expense's amount, shown in ₹
Category breakdown A derived list of each category's total and % share of the running total, sorted by amount
Theme toggle Light/dark, read via useContext by the app shell
Currency display toggle "Full" (₹1,50,000.00, Indian digit grouping) vs "compact" (₹1.5L), read via useContext by both the category breakdown and every individual expense row
Persistence The expense list is saved to localStorage a short delay after the latest change, and restored on the next load
Empty state A real message, not a blank list, when every expense has been deleted or cleared

Which Parts each feature uses

Feature Skills Part
expensesReducer - one pure function for add/edit/delete/clear, immutable updates throughout Action objects, a pure reducer, switch, spread/map/filter Part 10
useReducer(expensesReducer, STORAGE_KEY, loadInitialExpensesState) useReducer's signature and its lazy-init third argument Part 10
expensesReducer.test.jsx testing the reducer directly, no render Testing a reducer in isolation, as a plain function Part 10
ThemeProvider/useTheme - theme + currency display shared with no prop drilling createContext, a Provider, a custom useX hook with a safety throw Part 9
usePersistedExpenses - a useEffect that debounces a localStorage write and cancels the pending one via its cleanup function The dependency array, cleanup functions Part 6
usePersistedExpenses itself, as a reusable useXyz function Extracting stateful logic into a custom hook Part 7
The add-expense form and the inline edit form - controlled inputs, amount validated fresh on every render Controlled inputs, derive-don't-duplicate validation Part 5
The running total and the category breakdown - plain variables computed from expenses on every render Derived state, never copied into its own useState Part 6

💡 No fetch, no router - every piece of data this project touches is either hardcoded seed data or localStorage. That is deliberate: this project proves Parts 5-10 are enough to ship a real, persistent, themeable app, the same way the Stage 1 Menu Browser proved Parts 1-5 alone were enough for a smaller one.


Build it step by step

Build in small steps. Run the tests after every step. Do not open ExpenseTracker.jsx until you have tried each step yourself.

Step 1: The data and the reducer (Part 10)

What and why: decide the shape of one expense, and write every mutation as one pure function before any component exists to call it.

// data.js
export const CATEGORIES = ["rent", "groceries", "petrol", "electricity", "food", "other"];
export const seedExpenses = [
  { id: 1, date: "2026-10-01", amount: 15000, category: "rent", note: "October rent" },
  // ...six more, same as the Python CLI project's sample_expenses.json
];
// expensesReducer.js
export function expensesReducer(state, action) {
  switch (action.type) {
    case "add": {
      const id = nextExpenseId(state.expenses);
      return { expenses: [...state.expenses, { ...action.expense, id }] };
    }
    case "edit":
      return { expenses: state.expenses.map((e) => (e.id === action.id ? { ...e, ...action.patch } : e)) };
    case "delete":
      return { expenses: state.expenses.filter((e) => e.id !== action.id) };
    case "clear":
      return { expenses: [] };
    default:
      throw new Error(`Unknown action type: ${action.type}`);
  }
}

✅ Test: call expensesReducer({ expenses: [] }, { type: "add", expense: { ... } }) directly - no component - and check the id assigned and that the original state object is untouched.

Step 2: Lazy-restore from localStorage (Part 10, Section 5)

What and why: the list should survive a page refresh, but reading localStorage is work that should happen once, not on every render.

export function loadInitialExpensesState(storageKey) {
  const stored = window.localStorage.getItem(storageKey);
  if (stored === null) return { expenses: seedExpenses };
  try {
    return JSON.parse(stored);
  } catch {
    return { expenses: seedExpenses };
  }
}

Wire it with useReducer's third argument: useReducer(expensesReducer, STORAGE_KEY, loadInitialExpensesState).

✅ Test: pre-seed localStorage with a saved list and confirm a freshly-rendered app shows that list, not the seed data; confirm an empty localStorage falls back to the seed data.

Step 3: Theme and currency context (Part 9)

What and why: two settings that have nothing to do with any specific expense, read by components that have nothing to do with each other - the app shell and every individual row.

const ThemeContext = createContext(undefined);

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  const [currencyDisplay, setCurrencyDisplay] = useState("full");
  // ... toggle functions ...
  return <ThemeContext.Provider value={{ theme, toggleTheme, currencyDisplay, toggleCurrencyDisplay }}>{children}</ThemeContext.Provider>;
}

export function useTheme() {
  const context = useContext(ThemeContext);
  if (context === undefined) throw new Error("useTheme must be called inside a <ThemeProvider>");
  return context;
}

✅ Test: render two unrelated components inside the same ThemeProvider, toggle the theme from one, and confirm the other one's useTheme() call sees the new value; confirm calling useTheme() outside any provider throws.

Step 4: The add-expense form (Part 5)

What and why: validate the amount on every render - never a separate "is this valid" state - exactly the Menu Browser's quantity-field pattern, applied to money.

function validateAmount(rawValue) {
  if (rawValue.trim() === "") return "Enter an amount.";
  const amount = Number(rawValue);
  if (!Number.isFinite(amount) || amount <= 0) return "Amount must be a number greater than 0.";
  return null;
}

The "Add expense" button's disabled expression is just validateAmount(amount) !== null - computed fresh every render, never stored.

✅ Test: typing "0" or leaving the field blank shows the error and disables the button; a valid amount enables it and, on submit, adds a row and clears the form.

Step 5: The running total and category breakdown (Part 6)

What and why: both are fully computable from expenses on every render - no useState, no useEffect "keeping them in sync."

const total = expenses.reduce((sum, e) => sum + e.amount, 0);
const totalsByCategory = expenses.reduce((totals, e) => {
  totals[e.category] = (totals[e.category] ?? 0) + e.amount;
  return totals;
}, {});

✅ Test: deleting an expense immediately updates both the total and its category's share, with no extra render needed to "catch up."

Step 6: Persisting to localStorage (Parts 6-7)

What and why: writing to localStorage on every keystroke-driven render would be wasteful; debounce it, and cancel a pending write if a newer change arrives first - the same cancel-and-restart shape as Part 6's typing-indicator exercise.

export function usePersistedExpenses(storageKey, expenses, delayMs = 300) {
  useEffect(() => {
    const timeoutId = setTimeout(() => {
      window.localStorage.setItem(storageKey, JSON.stringify({ expenses }));
    }, delayMs);
    return () => clearTimeout(timeoutId);
  }, [storageKey, expenses, delayMs]);
}

✅ Test (fake timers): a change does not appear in localStorage immediately; it does appear once the delay elapses; a second change before the delay elapses cancels the first write and only the latest value is ever saved.

Step 7: Edit and delete per row (Parts 3, 5, 10)

What and why: each row owns its own "am I being edited right now" boolean - that is genuinely local, per-row UI state, not something that belongs in the shared reducer.

const [isEditing, setIsEditing] = useState(false);
// "Save" dispatches { type: "edit", id, patch }; "Cancel" just setIsEditing(false)

✅ Test: editing one row's amount/note and saving updates only that row and the total; clicking "Cancel" discards the draft with no dispatch at all; "Delete" removes exactly the clicked row.


Stretch goals

  • 🟢 A "Clear search"-style category filter <select> above the list (reuse the Menu Browser's exact pattern from Stage 1).
  • 🟢 Sort the expense list by date or amount, with a second controlled <select>.
  • 🟡 A month filter (YYYY-MM), the same date.slice(0, 7) trick the Python CLI project uses, applied to a controlled <input type="month">.
  • 🟡 A confirmation step before "Clear all expenses" actually dispatches (a second click within a few seconds, or a window.confirm).
  • 🔴 An "undo delete" - keep the last-deleted expense in a small bit of state and offer to re-add it for a few seconds (ties useEffect's cleanup, Part 6, to a timed UI affordance).
  • 🔴 A monthly budget per category, read from localStorage the same way the expense list is, with a warning once a category's total crosses it.

Checklist

  • I wrote expensesReducer as a single pure function with add/edit/delete/clear, and tested it directly with no component rendered.
  • I used useReducer's third argument to restore the list from localStorage on mount, and confirmed (with a call counter or similar) that the loader runs once, not once per render.
  • I shared theme and currency display through one ThemeProvider, read via useContext by at least two components that don't otherwise know about each other.
  • I validated the add-expense form's amount fresh on every render, with the "Add expense" button's disabled state derived from that validation, never stored separately.
  • I computed the running total and the category breakdown as plain variables from expenses, with no useState/useEffect pair "keeping them in sync."
  • I wrote a custom hook that debounces a localStorage write inside a useEffect, with a cleanup function that cancels a pending write when a newer one supersedes it - and proved both halves with fake timers.
  • I wired edit/delete per row, confirmed editing or deleting one row never touches any other row, and confirmed "Cancel" truly discards a draft without dispatching anything.
  • npx vitest run stage-2-intermediate/project-expense-tracker-ui passes, start to finish, twice in a row.

Next

🎉 Stage 2 done! Go back to the roadmap and start Stage 3, Part 11: Fetching data.

Search the guide