Skip to content
Tutorials Center
My learning

Topics

Lesson 113 of 132 ยท Projects

Project: Expense Tracker

Build an expense tracker in React with a reducer, money stored as integer cents, category totals, a bar chart made from plain elements, filters and a persistence plan.

An expense tracker adds money to the mix, and money teaches discipline. You need exact arithmetic, consistent formatting, and several views of the same list: the entries, the total, and a breakdown by category. All of those views must agree, which is the strongest argument for keeping one source of truth and deriving everything else.

We build it in three stages: the data rules as a tested reducer, the form and list, and the summary chart with filtering. Useful background: reducers, choosing state structure and forms and inputs.

The plan

  • An expense is { id, title, cents, category }. Amounts are stored as integer cents: 0.1 + 0.2 is not 0.3 in floating point, but 10 + 20 is exactly 30. We convert to dollars only for display, with Intl.NumberFormat.
  • The state is the list of expenses plus nextId. The total, the per-category totals and the filtered list are all computed during render.
  • Persistence: a real app would save the list to localStorage (or a server). The sandbox blocks storage, so the examples keep data in memory and the end of the lesson shows the read-only snippet to add.

Stage 1: the reducer and the summary

Stage 1: reducer and totals

No React hook was needed to test the rules: the reducer is a plain function, and the summary helper takes the list and returns totals.

Stage 2: the form and the list

The form turns the typed text into cents with Math.round(parseFloat(text) * 100), which rounds away the floating point noise of a value such as 19.99 * 100 = 1998.9999999999998. Invalid input (empty title, zero, negative or non-numeric amount) is rejected and an error message is shown with role="alert". The inputs are controlled (controlled and uncontrolled).

Stage 2: add and delete expenses

The reducer never sees a string: parsing and validation happen at the edge, in the form, so the rest of the app can trust that cents is a positive integer.

Stage 3: a chart and a filter

A chart does not need a library. A bar is a div whose width is a percentage of the largest category total. The filter is a category selected in state; the visible list is derived by filtering. Because the chart summarises all expenses while the list shows the filtered ones, clicking a bar can set the filter, and both views stay consistent since they come from the same array.

Stage 3: category chart and filter

Click a bar to filter, click it again to clear the filter. Delete an item and the chart, list and totals all update, because there is only one array.

Persisting the data

The sandbox blocks localStorage, so here is the shape of the code to add in a real app. Load once with the lazy initializer of useReducer, and save in an effect whenever the state changes:

JSX
function load() {
  try {
    return JSON.parse(localStorage.getItem('expenses')) ?? seed;
  } catch {
    return seed; // missing, corrupt or blocked storage
  }
}

const [state, dispatch] = useReducer(reducer, undefined, load);

useEffect(() => {
  try {
    localStorage.setItem('expenses', JSON.stringify(state));
  } catch {
    // storage full or unavailable: the app keeps working in memory
  }
}, [state]);

The try/catch matters: storage can be disabled, full or contain damaged data, and the app should still start. The same pattern is used at the end of the todo project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store amounts as integer cents?

    Integer arithmetic is exact. You convert to a decimal only when displaying the value.
  2. 2. Which values should NOT be stored in state in this app?

    Totals can be calculated from the list at any time. Storing them as well would create copies that could become inconsistent after an edit or delete.
  3. 3. Where should the amount text be parsed and validated?

    Validating at the boundary keeps the reducer simple and guarantees the rest of the app only sees positive integer cents.
  4. 4. Why wrap the localStorage calls in try/catch?

    Private modes, disabled cookies, quota errors and damaged data all cause exceptions. Falling back to defaults keeps the app usable.

Summary

  • Keep money as integer cents and format it with Intl.NumberFormat when displaying.
  • One reducer owns the list; totals, chart bars and the filtered view are derived during render.
  • Parse and validate input in the form so the reducer only receives clean data.
  • A bar chart can be plain elements with computed widths; make bars buttons so they are keyboard-accessible.
  • To persist, load with the lazy useReducer initializer and save in an effect, guarding storage access with try/catch.

Next: Project: Currency Converter