Skip to content
Tutorials Center
My learning

Topics

Lesson 109 of 132 ยท Projects

Project: Calculator

Build a working calculator in React with a pure reducer that handles digits, operators, equals, clear and errors, then add keyboard support with a safe effect.

A calculator is a state machine in disguise. At any moment it is in one of a few situations: typing the first number, just pressed an operator, typing the second number, or showing a result. A reducer is the natural way to model that, because every button press is an action and the rules live in one pure function you can test without a screen.

You will build it in three stages: the reducer on its own, the keypad around it, and keyboard support.

The plan

The state needs four things:

  • current: the string being typed (we keep it as a string so 0. and 1.50 can exist while typing).
  • previous: the number stored before an operator was pressed, or null.
  • operator: '+', '-', 'ร—', 'รท' or null.
  • overwrite: true right after a result, so the next digit starts a fresh number.

The actions are digit, dot, operator, equals, clear, delete and negate. Floating point numbers can show noise like 0.1 + 0.2 = 0.30000000000000004, so results are rounded to 10 decimal places.

Stage 1: the reducer, tested without UI

Stage 1: the calculator reducer

The reducer is a plain function of (state, action), so we tested it by replaying key presses. Notice two design choices. First, the overwrite flag removes a whole class of bugs: after = the next digit starts a new number, while an operator continues with the result. Second, an invalid result (division by zero) becomes the string 'Error', and every case checks for it.

Stage 2: the keypad

Now we put buttons around it. The keys are data, an array of rows, so the layout is map rather than twenty copy-pasted buttons (lists and keys). A small Display uses aria-live so screen readers hear results.

Stage 2: the calculator UI

The component contains no arithmetic at all: it renders state and dispatches. That is the payoff of the reducer.

Stage 3: keyboard support

A real calculator works with the keyboard. We listen for keydown on the window inside an effect and translate keys into the same actions the buttons use. The cleanup removes the listener (effect cleanup). Because dispatch is stable, the effect has no dependencies that change.

Stage 3: keyboard handling

To finish the project, replace the setLog call with dispatch(action) from the Stage 2 component and keep keyToAction as is. Two details matter. We ignore keys pressed with Ctrl, Cmd or Alt so browser shortcuts such as copy still work. And preventDefault() stops Enter from also "clicking" a focused button, which would press it twice.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the current number stored as a string while typing?

    Number('1.50') becomes 1.5 and '0.' becomes 0, so the user's typing would be altered. We convert to a number only when computing.
  2. 2. What does the overwrite flag do?

    After an operator or equals, the displayed number is finished. A digit must replace it, while an operator can still use it.
  3. 3. Why does the keyboard effect return a function that calls removeEventListener?

    Window listeners outlive the component. Cleanup removes the old one when the effect re-runs or the component unmounts.
  4. 4. What is the main benefit of putting the rules in a reducer here?

    One pure function owns every rule, so the UI and the keyboard handler both just report what the user did.

Summary

  • A calculator is a small state machine; a reducer keeps all its rules in one pure, testable function.
  • Keep typed numbers as strings and convert only when computing; round results to hide floating point noise.
  • Describe keys as data and render them with map.
  • Add keyboard support with a window keydown listener in an effect, with cleanup, ignoring modifier keys.
  • Represent invalid results (division by zero) explicitly and handle them in every action.

Next: Project: Weather App