Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 71 ยท Projects

Project: Calculator and Stopwatch

Build two classic React Native apps: a calculator with a pure reducer and a stopwatch with start, stop, reset and laps, with logic tested as plain functions.

Two small apps, two different kinds of state. A calculator is driven by button presses, so it is a perfect fit for a reducer: the same press always does the same thing to the same state. A stopwatch is driven by time, so it teaches the part that goes wrong most often in React Native: timers that must start, stop and clean up properly.

Both follow the habit of earlier projects: write the logic as plain functions you can run and check anywhere, then wrap them in a screen.

What runs on this site. The React Native screens are read-only here because they need a native runtime. The logic (the calculator reducer, the time formatter) is real, runnable JavaScript, and each project has a runnable stand-in that draws the same UI with HTML.

Part 1: the calculator

The state and the actions

The calculator's whole state is four fields, the same idea as any pocket calculator: what is on the display, the stored left operand, the pending operator, and whether the next digit starts a new number.

JavaScript
export const initialState = { display: '0', stored: null, operator: null, fresh: false };

Every key is an action: { type: 'digit', value: '7' }, { type: 'operator', value: '+' }, { type: 'equals' }, { type: 'clear' }, { type: 'dot' }, { type: 'sign' }, { type: 'percent' }. A reducer takes the state and an action and returns the next state, with no side effects.

JavaScript
const compute = (a, op, b) => ({ '+': a + b, '-': a - b, '*': a * b, '/': b === 0 ? NaN : a / b }[op]);
const tidy = (n) => String(parseFloat(n.toPrecision(12)));   // hides 0.1 + 0.2 = 0.30000000000000004

export function reducer(state, action) {
  switch (action.type) {
    case 'digit':
      return state.fresh || state.display === '0' || isNaN(state.display)
        ? { ...state, display: action.value, fresh: false }
        : { ...state, display: state.display + action.value };
    case 'dot':
      if (state.fresh) return { ...state, display: '0.', fresh: false };
      return state.display.includes('.') ? state : { ...state, display: state.display + '.' };
    case 'operator': {
      if (state.operator && state.fresh) return { ...state, operator: action.value };   // replace
      const base = state.operator ? finish(state) : state;
      return { display: base.display, stored: parseFloat(base.display), operator: action.value, fresh: true };
    }
    case 'equals':
      return state.operator ? { ...finish(state), operator: null, stored: null, fresh: true } : state;
    case 'sign':
      return state.display === '0' ? state : { ...state, display: state.display.startsWith('-') ? state.display.slice(1) : '-' + state.display };
    case 'percent':
      return { ...state, display: tidy(parseFloat(state.display) / 100) };
    case 'clear':
      return initialState;
    default:
      return state;
  }
}

function finish(state) {
  const result = compute(state.stored, state.operator, parseFloat(state.display));
  return { ...state, display: Number.isNaN(result) ? 'Cannot divide by 0' : tidy(result) };
}

Three decisions are worth noticing. The display is kept as a string, so a trailing dot ("12.") is not lost by parseFloat. Two operators in a row replace the operator instead of calculating. And tidy rounds to 12 significant digits so that binary floating-point noise never reaches the screen.

The screen

JSX
import { useReducer } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
import { reducer, initialState } from './calculator';

const KEYS = [
  ['clear', 'sign', 'percent', '/'],
  ['7', '8', '9', '*'],
  ['4', '5', '6', '-'],
  ['1', '2', '3', '+'],
  ['0', 'dot', 'equals'],
];

function toAction(key) {
  if (/^\d$/.test(key)) return { type: 'digit', value: key };
  if ('+-*/'.includes(key)) return { type: 'operator', value: key };
  return { type: key };
}

export function Calculator() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <View style={styles.pad}>
      <Text style={styles.display} numberOfLines={1} adjustsFontSizeToFit accessibilityLiveRegion="polite">
        {state.display}
      </Text>
      {KEYS.map((row, i) => (
        <View key={i} style={styles.row}>
          {row.map((key) => (
            <Pressable key={key} style={styles.key} onPress={() => dispatch(toAction(key))} accessibilityLabel={key}>
              <Text style={styles.keyText}>{labels[key] ?? key}</Text>
            </Pressable>
          ))}
        </View>
      ))}
    </View>
  );
}

adjustsFontSizeToFit (iOS) and numberOfLines={1} keep a long number on one line by shrinking it. In a grid built from rows, flex: 1 on each key makes the columns equal. Give every key an accessibilityLabel that spells out the symbol (for example "divide") because a screen reader may skip รท.

Calculator reducer with a scripted key sequence

The checks use the exact reducer that drives the keypad: 2 + 3 + 4 finishes the first addition when the second + is pressed, .1 + .2 shows 0.3, 5 + * 3 replaces the operator, and division by zero shows a message instead of Infinity.

Part 2: the stopwatch

Time is not a counter

The obvious stopwatch adds 10 to a number every 10 ms. It drifts, because timers are not exact and a busy JavaScript thread delays them; after a minute the display can be seconds off. The correct design stores timestamps and calculates the elapsed time from the clock each time it renders:

  • startedAt: the Date.now() (or performance.now()) value when the clock last started running.
  • accumulated: the milliseconds that passed in earlier runs, before the last stop.
  • elapsed = accumulated + (running ? now - startedAt : 0).

The timer's only job is to cause a re-render a few times per second; the accuracy comes from the clock.

JavaScript
export function elapsedMs(watch, now) {
  return watch.accumulated + (watch.startedAt === null ? 0 : now - watch.startedAt);
}

export function start(watch, now) {
  return watch.startedAt === null ? { ...watch, startedAt: now } : watch;
}

export function stop(watch, now) {
  return watch.startedAt === null ? watch : { ...watch, accumulated: elapsedMs(watch, now), startedAt: null };
}

export function lap(watch, now) {
  const total = elapsedMs(watch, now);
  const previous = watch.laps.length ? watch.laps[0].total : 0;
  return { ...watch, laps: [{ total, split: total - previous }, ...watch.laps] };
}

export function format(ms) {
  const cs = Math.floor(ms / 10) % 100;
  const s = Math.floor(ms / 1000) % 60;
  const m = Math.floor(ms / 60000);
  const pad = (n, w = 2) => String(n).padStart(w, '0');
  return `${pad(m)}:${pad(s)}.${pad(cs)}`;
}

The screen and its timer

JSX
import { useEffect, useState } from 'react';

export function Stopwatch() {
  const [watch, setWatch] = useState({ accumulated: 0, startedAt: null, laps: [] });
  const [now, setNow] = useState(Date.now());
  const running = watch.startedAt !== null;

  useEffect(() => {
    if (!running) return;
    const id = setInterval(() => setNow(Date.now()), 50);
    return () => clearInterval(id);          // cleanup when stopped or unmounted
  }, [running]);

  return (
    <View style={{ padding: 24, gap: 12 }}>
      <Text style={{ fontSize: 48, fontVariant: ['tabular-nums'] }}>{format(elapsedMs(watch, now))}</Text>
      <Button title={running ? 'Stop' : 'Start'} onPress={() => setWatch((w) => (running ? stop(w, Date.now()) : start(w, Date.now())))} />
      <Button title="Lap" onPress={() => setWatch((w) => lap(w, Date.now()))} disabled={!running} />
      <Button title="Reset" onPress={() => setWatch({ accumulated: 0, startedAt: null, laps: [] })} />
    </View>
  );
}

Two details deserve emphasis. The effect depends on running and returns a cleanup that clears the interval: without it, leaving the screen leaves a timer alive, calling setNow on an unmounted component (see Common Pitfalls). And fontVariant: ['tabular-nums'] makes every digit the same width, so the display does not wobble as the numbers change.

A stopwatch also has to handle backgrounding. When the app goes to the background, JavaScript timers pause, but because the elapsed time is computed from Date.now(), it is still correct when the user comes back. A counter-based stopwatch would be wrong by the whole time the app was away.

Stopwatch logic with a fake clock, plus a live stopwatch

The fake clock proves that the paused 4 seconds are not counted: the second run starts at 10000 with 5.0 s already accumulated, so at 12345 the elapsed time is 7.345 s, shown as 00:07.34.

Ideas to extend

  • Save laps with AsyncStorage so they survive a restart.
  • Add a countdown timer: the same timestamp idea with endsAt - now, and a haptic or notification at zero.
  • Add an AppState listener to show a "still running" notification when the app goes to the background.
  • Format hours once ms passes one hour.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is the calculator display kept as a string?

    parseFloat("12.") is 12. A string keeps exactly what the user typed until the calculation happens.
  2. 2. Why does a stopwatch store start timestamps instead of counting ticks?

    Computing elapsed time from the clock stays correct even when timers are late or paused; counting ticks accumulates error.
  3. 3. What does the cleanup function returned from the useEffect do in the stopwatch?

    Without clearInterval, the timer would keep running and update state after the component is gone.
  4. 4. What does 5 + * 3 = give in the reducer and why?

    An operator pressed right after another operator replaces it, so the pending operation is multiplication.

Summary

  • A calculator is a reducer over { display, stored, operator, fresh }: keep the display as a string, replace repeated operators and round floating-point noise.
  • Write the logic as pure functions and test it with scripted key presses before building the UI.
  • A stopwatch stores timestamps (startedAt, accumulated) and derives the elapsed time; the interval only triggers re-renders.
  • Always clean up timers in the effect's return function.

Next: Project: Number Guessing, OTP and Random Numbers.