Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 71 ยท Projects

Project: Habit and Fitness Tracker

Build a habit and fitness tracker in React Native: a SQLite schema, streak logic, SVG bar charts, daily reminders and animated progress, with runnable stand-ins.

The last project brings the advanced pieces together. A habit and fitness tracker keeps structured data over months (so it needs a real database, not a single JSON blob), turns that data into numbers and pictures (streaks and charts), reminds the user at the right time and gives visual feedback when a goal is reached.

You will design a SQLite schema and the queries around it, write the streak logic as plain functions, draw a bar chart with SVG, schedule a daily local notification and animate a progress indicator. This is the biggest project in the track, so it leans on earlier lessons: Local Databases with SQLite, Push Notifications, Animations with the Animated API and Images, Icons and Media.

What runs on this site. SQLite, notifications and native SVG need a device, so those parts are read-only code. The runnable stand-ins are real JavaScript for the date and streak logic, and an HTML <svg> chart that uses the same scale math you would give react-native-svg. Dates and minutes in the demos are invented sample data, and "today" is fixed so every run is identical.

What the app does

Four building blocks

SQLite Habits and daily check-ins.
Streaks Consecutive days, computed.
Chart Minutes per day as SVG bars.
Reminder One local notification per day.

Plus an animated ring for today's goal.

1 / 2

The database schema

Two tables are enough. A habit is something you track ("Run", "Read"). A check-in records how many minutes you did on one calendar day. The primary key (habit_id, day) makes it impossible to have two rows for the same habit on the same day, which turns "log minutes for today" into a simple upsert.

SQL
CREATE TABLE IF NOT EXISTS habits (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  name        TEXT NOT NULL,
  goal_minutes INTEGER NOT NULL DEFAULT 30 CHECK (goal_minutes > 0),
  created_at  TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS checkins (
  habit_id INTEGER NOT NULL REFERENCES habits(id) ON DELETE CASCADE,
  day      TEXT    NOT NULL,           -- 'YYYY-MM-DD', the user's local date
  minutes  INTEGER NOT NULL CHECK (minutes >= 0),
  PRIMARY KEY (habit_id, day)
);

CREATE INDEX IF NOT EXISTS idx_checkins_day ON checkins(day);

Store the day as a local date string such as 2026-03-15, not as a UTC timestamp. A streak is about the user's calendar days; a timestamp near midnight in a different time zone would land on the wrong day. Notice also that foreign keys are off by default in SQLite connections, so the app must turn them on with PRAGMA foreign_keys = ON for ON DELETE CASCADE to work.

The expo-sqlite setup creates the schema once and tracks a version number, so later releases can migrate:

JSX
import { SQLiteProvider, useSQLiteContext } from 'expo-sqlite';

async function migrate(db) {
  const row = await db.getFirstAsync('PRAGMA user_version');
  let version = row?.user_version ?? 0;

  if (version < 1) {
    await db.execAsync(`
      PRAGMA journal_mode = WAL;
      PRAGMA foreign_keys = ON;
      CREATE TABLE habits (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, goal_minutes INTEGER NOT NULL DEFAULT 30);
      CREATE TABLE checkins (
        habit_id INTEGER NOT NULL REFERENCES habits(id) ON DELETE CASCADE,
        day TEXT NOT NULL,
        minutes INTEGER NOT NULL,
        PRIMARY KEY (habit_id, day)
      );
    `);
    version = 1;
  }

  await db.execAsync('PRAGMA user_version = ' + version);
}

export default function App() {
  return (
    <SQLiteProvider databaseName="habits.db" onInit={migrate}>
      <HabitsScreen />
    </SQLiteProvider>
  );
}

PRAGMA user_version is a free integer slot stored inside the database file, which makes it a lightweight migration counter. Always use parameters (?) for values from the user, never string concatenation:

JSX
function HabitsScreen() {
  const db = useSQLiteContext();

  async function logMinutes(habitId, day, minutes) {
    await db.runAsync(
      `INSERT INTO checkins (habit_id, day, minutes) VALUES (?, ?, ?)
       ON CONFLICT(habit_id, day) DO UPDATE SET minutes = excluded.minutes`,
      [habitId, day, minutes]
    );
  }

  async function lastDays(habitId, fromDay) {
    return db.getAllAsync(
      'SELECT day, minutes FROM checkins WHERE habit_id = ? AND day >= ? ORDER BY day',
      [habitId, fromDay]
    );
  }
  // ...
}

ON CONFLICT ... DO UPDATE is SQLite's upsert, so one statement handles both "first log of the day" and "change today's number". The day >= ? comparison works on plain strings because ISO dates sort alphabetically in date order.

Streaks are just date math

A streak is the number of consecutive days, ending today, with at least one check-in. There is one friendly rule: if today is not done yet, the streak is not broken, it just ends yesterday. We implement it with day numbers so we never fight daylight-saving shifts: convert each YYYY-MM-DD string into "days since 1970" using Date.UTC.

Streak and weekly helpers on fixed dates

The three streak lines show the friendly rule at work: logging today gives 3 (the run 4th, 5th, 6th of March), not logging yet on the 7th still gives 3, and only skipping a whole day resets it to 0. The month boundary line proves that using day numbers handles the move from February to March without special cases.

Charts with SVG

React Native has no built-in chart or drawing component. The standard tool is react-native-svg, which lets you write <Svg>, <Rect>, <Line> and <Text> as native views. Because drawing is just geometry, the only real work is a scale: converting a value in minutes into a height in pixels. The same function works for any chart library or hand-drawn chart.

JSX
import Svg, { Line, Rect, Text as SvgText } from 'react-native-svg';

const W = 320, H = 160, PAD = 24;

export function MinutesChart({ points, goal }) {
  const max = Math.max(goal, ...points.map((p) => p.minutes), 1);
  const barW = (W - PAD * 2) / points.length;
  const y = (minutes) => H - PAD - (minutes / max) * (H - PAD * 2);

  return (
    <Svg width={W} height={H} accessibilityLabel="Minutes per day for the last 7 days">
      <Line x1={PAD} x2={W - PAD} y1={y(goal)} y2={y(goal)} stroke="#f59e0b" strokeDasharray="4 4" />
      {points.map((p, i) => (
        <Rect
          key={p.day}
          x={PAD + i * barW + 4}
          y={y(p.minutes)}
          width={barW - 8}
          height={H - PAD - y(p.minutes)}
          rx={4}
          fill={p.minutes >= goal ? '#16a34a' : '#3b82f6'}
        />
      ))}
      {points.map((p, i) => (
        <SvgText key={p.day + 't'} x={PAD + i * barW + barW / 2} y={H - 8} fontSize="10" textAnchor="middle">
          {p.day.slice(8)}
        </SvgText>
      ))}
    </Svg>
  );
}

Two habits make a chart honest and robust. The maximum includes the goal, so the goal line is always on the chart. And Math.max(..., 1) prevents a division by zero when every value is 0. Add accessibilityLabel and, ideally, a text summary near the chart ("5 of 7 days at goal"), because a picture alone is not available to screen readers. On this site the SVG below renders as ordinary HTML, but the coordinates come from the identical math.

Reminders

A habit app lives or dies by reminders. You do not need a server for this: local notifications are scheduled on the device. With expo-notifications the flow is: ask permission, then schedule a repeating trigger.

JSX
import * as Notifications from 'expo-notifications';

export async function scheduleDailyReminder(hour, minute) {
  const { status } = await Notifications.requestPermissionsAsync();
  if (status !== 'granted') return null; // explain how to enable it in Settings

  await Notifications.cancelAllScheduledNotificationsAsync();
  return Notifications.scheduleNotificationAsync({
    content: { title: 'Time for your habit', body: 'A few minutes today keeps the streak alive.' },
    trigger: {
      type: Notifications.SchedulableTriggerInputTypes.DAILY,
      hour,
      minute,
    },
  });
}

Ask for permission when the user turns the reminder on, not at launch, so the system dialog appears with a clear reason. Save the returned identifier so you can cancel exactly that reminder when the user changes the time, and handle the denied case with a friendly explanation. On Android you also need a notification channel; those platform details are in Push Notifications.

Animated feedback

When the user reaches the goal, a small animation turns a number change into a moment. A progress bar can be driven with Animated.timing and an interpolation from 0..1 to a width percentage:

JSX
import { useEffect, useRef } from 'react';
import { Animated, View } from 'react-native';

function ProgressBar({ progress }) {            // progress between 0 and 1
  const value = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(value, { toValue: progress, duration: 400, useNativeDriver: false }).start();
  }, [progress, value]);

  const width = value.interpolate({ inputRange: [0, 1], outputRange: ['0%', '100%'] });

  return (
    <View style={{ height: 10, borderRadius: 5, backgroundColor: '#e2e8f0' }}>
      <Animated.View style={{ height: 10, borderRadius: 5, width, backgroundColor: '#16a34a' }} />
    </View>
  );
}

useNativeDriver: false is required here because width is a layout property and the native driver can only animate non-layout properties such as opacity and transform. For smoother results you can animate transform: [{ scaleX }] instead, or move to Reanimated (Reanimated and Gesture Handler).

The runnable tracker

The stand-in below is one habit with a fixed "today" (2026-03-15). Each day of the last week has a +10 min button, the chart redraws, the streak updates and the ring fills with a CSS transition. Writing to the database is replaced by React state, but the helper functions are the same ones you would call with query results.

Habit tracker with streak, SVG chart and progress ring (stand-in)

Press +10 on the 15th three times: the ring fills, the bar turns green at 30 minutes and the streak grows to 4, because the 12th, 13th, 14th and 15th are now all logged. Then press Reset week and watch everything fall back to zero. The ring animation is a CSS transition here; in the real app it is the Animated or Reanimated value from the previous section.

Ideas to take it further

  • Several habits with a picker and a stacked or small-multiples chart.
  • Export and backup by reading the tables and sharing a CSV with the Share API.
  • Health data from the platform health APIs (these need native modules and careful privacy handling; see Native Modules, Expo Modules and Config Plugins).
  • Tests for currentStreak and the scale function: pure functions are the cheapest tests you will ever write (Testing React Native Apps).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does checkins use PRIMARY KEY (habit_id, day)?

    A composite primary key forbids duplicates for the same habit and day. INSERT ... ON CONFLICT DO UPDATE can then insert the first log or update later ones.
  2. 2. Why store the day as a local date string instead of a UTC timestamp?

    A habit streak counts calendar days in the user's time zone. A plain YYYY-MM-DD string avoids time zone shifts and still sorts correctly.
  3. 3. A user has logged the last three days but not yet today. What should the current streak show?

    The helper starts from yesterday when today is not logged, so the streak stays alive until the day ends without a check-in.
  4. 4. Why does the Animated progress bar use useNativeDriver: false?

    Layout properties are computed on the JavaScript side and the native driver cannot animate them. Animating transform scaleX is an alternative that can use the native driver.

Summary

  • Model habits and daily check-ins with a composite primary key, local-date strings, parameterized queries, upserts and a user_version migration counter.
  • Compute streaks with day numbers (Date.UTC) so month and daylight-saving boundaries never matter, and do not punish a user whose day is not over.
  • Draw charts with react-native-svg using a simple value-to-pixel scale; include the goal in the maximum and add an accessible text summary.
  • Schedule daily reminders as local notifications after asking for permission at a meaningful moment.
  • Animate progress with Animated (non-layout properties can use the native driver) or Reanimated.
  • On this site the database, notifications and native SVG are read-only; the date logic and the chart math run for real in HTML stand-ins.

You have finished the projects. Next, practice what you learned in Exercises: Components, Styles and Lists.