Expense Tracker
What you'll build
An expense tracker where you add expenses with a description and amount, see a list of all expenses, and view the total. Uses useReducer for state management.
Goals
- Use useReducer for expense state
- Define reducer actions (add, delete)
- Calculate total from state
- Render expense list and total
Prerequisites
- useReducer basics
- Form inputs
- List rendering
Steps
- 1
Define the reducer and initial state
Create a reducer that handles 'add' and 'delete' actions, and initialize with an empty expenses array.
Codefunction reducer(state, action) { switch (action.type) { case "add": return [...state, { id: Date.now(), ...action.expense }]; case "delete": return state.filter(e => e.id !== action.id); default: return state; } } const [expenses, dispatch] = useReducer(reducer, []);Expected result
Reducer is ready to manage expenses.
- 2
Add the expense form
Create a form with description and amount inputs that dispatches an 'add' action on submit.
Codeconst [desc, setDesc] = useState(""); const [amount, setAmount] = useState(""); const handleSubmit = (e) => { e.preventDefault(); dispatch({ type: "add", expense: { desc, amount: parseFloat(amount) } }); setDesc(""); setAmount(""); };Expected result
Submitting the form adds a new expense.
- 3
Render the expense list and total
Map over expenses to show each one with a delete button, and calculate the total with reduce.
Code{expenses.map(exp => ( <div key={exp.id}> {exp.desc}: ${exp.amount} <button onClick={() => dispatch({ type: "delete", id: exp.id })}>Delete</button> </div> ))} <h3>Total: ${expenses.reduce((sum, e) => sum + e.amount, 0)}</h3>Expected result
Expenses are listed with delete buttons and a running total.
- 4
Add state management & event handling
Use useState to manage component state and add onClick/onChange handlers to interactive elements. State is the heart of React components, and event handling lets them respond to user actions.
Codeimport { useState } from "react"; export function MyComponent() { const [count, setCount] = useState(0); const [text, setText] = useState(""); return ( <div> <button onClick={() => setCount(c => c + 1)}> Count: {count} </button> <input value={text} onChange={(e) => setText(e.target.value)} /> </div> ); }Expected result
Clicking the button increments the count; the input content updates in real time as you type.
- 5
Add Props validation & component split
Define a Props interface (TypeScript) or propTypes for the component, and split large components into smaller sub-components. Type-safe Props make the component interface clear and reusable.
Codeinterface ChildProps { label: string; value: number; onChange: (v: number) => void; } function Child({ label, value, onChange }: ChildProps) { return ( <label> {label} <input type="number" value={value} onChange={(e) => onChange(Number(e.target.value))} /> </label> ); }Expected result
The child component receives type-safe Props; the parent can reuse it to render multiple fields.
Try it yourself
What you learned
You learned to use useReducer for structured state management with typed actions. This pattern scales better than multiple useState calls when state transitions are complex or interrelated.
Related Resources
Related Lessons
- useReducer
Reducer pattern for state management.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.