Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 38 ยท Projects and Practice

Project: A Habit Tracker

Build an offline-first habit tracker in Expo: plan screens and data, write tested streak logic, store check-ins in SQLite, schedule daily reminders and prepare the first release.

Time to combine the pieces. A habit tracker is a perfect first real app: small enough to finish, but it needs navigation, local data, date logic, notifications and a release. Users create habits ("Read 20 minutes"), tap to check one off each day, see their current streak and get a reminder in the evening.

We will design it, build the heart of it (the data and streak logic) as plain, testable JavaScript, and show how each part connects to the Expo modules from this chapter.

What runs on this site. The screens use native modules, so the Expo code is read-only. The streak logic, the SQLite schema and the reminder time calculation are plain JavaScript and SQL and run here (SQLite through Node's node:sqlite).

1. Plan the app

flowchart TD
  A["Today screen<br/>(list, tap to check)"] --> B["Habit detail<br/>(streak, history)"]
  A --> C["New habit form<br/>(name, reminder time)"]
  D["SQLite<br/>habits + checkins"] --- A
  D --- B
  E["Notifications<br/>daily reminder"] --- C

Three screens, one database, one scheduler.

With Expo Router the files could be:

TEXT
app/
  _layout.jsx          # SQLiteProvider + Stack
  index.jsx            # Today
  habit/[id].jsx       # Detail
  new.jsx              # New habit (presented as a modal)
src/
  db.js                # schema + queries
  streak.js            # pure logic
  reminders.js         # notifications

Keep streak.js free of React and Expo imports. Pure code is easy to test (Testing with Jest).

2. The data

Two tables are enough. A check-in is one row per habit per local calendar day, stored as YYYY-MM-DD. Storing the day as text avoids time zone confusion: "Tuesday" is Tuesday where the user is.

Node.js Schema and queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the app each statement becomes db.runAsync / db.getAllAsync (expo-sqlite lesson) and the schema goes into a PRAGMA user_version migration.

3. The streak logic

A current streak is the number of consecutive days, ending today or yesterday, on which the habit was done. It ends at yesterday because today is not over: if you did not check in yet, the streak is still alive until midnight.

The longest streak is the longest run of consecutive days anywhere in the history.

Node.js streak.js with tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four decisions here are worth copying in other projects: days are plain strings, date math happens in UTC at midnight, a Set makes lookups cheap, and the "today is still open" rule is explicit and tested.

4. The Today screen

JSX
// app/index.jsx
import { useCallback, useState } from 'react';
import { FlatList, Pressable, Text, View } from 'react-native';
import { useFocusEffect, Link } from 'expo-router';
import { useSQLiteContext } from 'expo-sqlite';
import { todayString } from '../src/streak';

export default function Today() {
  const db = useSQLiteContext();
  const [habits, setHabits] = useState([]);
  const today = todayString();

  const load = useCallback(async () => {
    setHabits(await db.getAllAsync(
      `SELECT h.id, h.name,
         EXISTS (SELECT 1 FROM checkins c WHERE c.habit_id = h.id AND c.day = ?) AS done
       FROM habits h ORDER BY h.id`, today));
  }, [db, today]);

  useFocusEffect(useCallback(() => { load(); }, [load]));   // refresh when returning to the screen

  async function toggle(habit) {
    if (habit.done) await db.runAsync('DELETE FROM checkins WHERE habit_id = ? AND day = ?', habit.id, today);
    else await db.runAsync('INSERT OR IGNORE INTO checkins (habit_id, day) VALUES (?, ?)', habit.id, today);
    load();
  }

  return (
    <FlatList
      data={habits}
      keyExtractor={(h) => String(h.id)}
      ListEmptyComponent={<Text>No habits yet. Tap + to add one.</Text>}
      renderItem={({ item }) => (
        <Pressable onPress={() => toggle(item)} accessibilityRole="checkbox" accessibilityState={{ checked: !!item.done }}>
          <Text>{item.done ? 'โœ…' : 'โฌœ'} {item.name}</Text>
        </Pressable>
      )}
    />
  );
}

todayString() must use the device's local date (build it from getFullYear, getMonth, getDate), not toISOString(), which would give the UTC date and flip to "tomorrow" in the evening for users west of Greenwich.

5. Reminders

When a habit has a reminder time such as 20:30, schedule a daily notification with a stable identifier, so editing replaces it (Scheduling local notifications):

JSX
// src/reminders.js
import * as Notifications from 'expo-notifications';

export async function scheduleHabitReminder(habit) {
  const id = `habit-${habit.id}`;
  await Notifications.cancelScheduledNotificationAsync(id);
  if (!habit.reminder) return;

  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== 'granted') return;

  const [hour, minute] = habit.reminder.split(':').map(Number);
  await Notifications.scheduleNotificationAsync({
    identifier: id,
    content: { title: habit.name, body: 'Keep your streak going!', data: { habitId: habit.id } },
    trigger: { type: Notifications.SchedulableTriggerInputTypes.DAILY, hour, minute },
  });
}

A nicer touch: skip the reminder when the habit is already done today. That needs a rolling schedule of single DATE notifications that you recompute on each app open, because a repeating daily trigger cannot look at your database.

Node.js Smart reminders: skip a day that is already done

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

6. Polish checklist

  • Empty state and a friendly first-run message.
  • Haptics on check-in (expo-haptics), and an accessible label on every control.
  • Dark mode with useColorScheme and a userInterfaceStyle: "automatic" setting.
  • Backup: export history as JSON with expo-sharing.
  • Tests: streak logic (above) and a component test for the Today screen with a mocked database.
  • Release: icon, splash, a production profile, eas build, TestFlight/internal track (EAS Build profiles, Submitting).

Ideas to extend it

  1. Weekly goals ("3 times a week") instead of every day.
  2. A heat-map calendar of the last 90 days.
  3. Home-screen widgets (via a config plugin and native widget code).
  4. Cloud backup, building on the offline sync project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store check-in days as YYYY-MM-DD text?

    A habit day is a calendar concept in the user's local time, so a plain date string models it exactly.
  2. 2. A user has not checked in today yet, but did yesterday and the day before. What is the current streak?

    The streak ends at yesterday while today is unfinished.
  3. 3. How does PRIMARY KEY (habit_id, day) help?

    The database itself guarantees one row per habit per day.
  4. 4. Why should streak.js not import React or Expo modules?

    Separating logic from UI makes tests simple and fast.

Summary

  • Plan screens, data and side effects (notifications) before coding.
  • Model a day as a local calendar date string; let the database enforce uniqueness.
  • Put streak rules in a tested pure module and keep screens thin.
  • Use stable notification identifiers so edits replace reminders.
  • Finish with polish, tests and a release through EAS.

Next: Project: offline notes with sync