Profile
Back to NewsBack
Dev.to 11 min
Reader Mode
Building Real Time React Native apps with LiveStore, Measure.sh and Claude Code

Building Real Time React Native apps with LiveStore, Measure.sh and Claude Code

1 day ago

Introducing SplitSync

SplitSync is a small app for friends on a trip who pay for things as they go and settle up at the end. One person books the villa, someone else covers the cab, and dinner gets split four ways, except only three people ordered drinks.

It has two screens. The dashboard shows the trip total, everyone's balance, who should pay whom, a category breakdown and the latest expenses. The second screen is where an expense is added or edited, with a live preview of the split.

Even for an app this small, a few things have to be right:

Requirement What goes wrong without it
Exact money Floats drift. ₹100 split three ways must add back up to ₹100.
One source of truth An edit on one card and a stale total on another.
Works offline Beach shacks don't have good Wi-Fi.
Stays fast as data grows A trip with a thousand expenses freezes the dashboard on every save.

There's one more. It's a finance app, so amounts, expense titles and names should never show up in the telemetry. Writing a privacy rule is the easy part. Checking what actually leaves the phone is harder, and that became a big part of this project.

The stack

  • React Native 0.81 + Expo SDK 54, with the New Architecture and Expo Router. SDK 54 is a deliberate choice: @livestore/[email protected] needs expo-sqlite ^16, and SDK 54 is the last release that ships it.
  • LiveStore 0.5.1 with its Expo adapter. Events go into an eventlog, materializers turn them into SQLite tables, and queries update on their own when the data changes.
  • Measure: @measuresh/react-native 0.6.0, which bundles the Android SDK 0.24.0. It's an open-source mobile monitoring platform that can also be self-hosted.
  • Claude Code with the Measure MCP server.

A development build is required. Both SDKs ship native code, so Expo Go can't run them.


NOTE: Sync is optional in SplitSync. LiveStore can sync through a Cloudflare Worker, and the repo includes one, but it's turned off here. We already covered offline sync with Turso, so this demo focuses on event sourcing, reactive queries and performance.

Storing expenses as events with LiveStore

LiveStore keeps what happened separate from what the app shows. Every action is an event, and events are versioned and never edited:

// src/livestore/schema.ts (simplified)
export const events = {
  expenseCreated: Events.synced({
    name: 'v1.ExpenseCreated',
    schema: Schema.Struct({
      id: Schema.String, title: Schema.String, category: Schema.String,
      amountMinor: Schema.Number, paidBy: Schema.String,
      participants: Schema.Array(Schema.String), createdAt: Schema.Number, isSeed: Schema.Boolean,
    }),
  }),
  expenseUpdated: /* … */, expenseDeleted: /* … */, settlementRecorded: /* … */,
}

Amounts are stored as whole paise (₹1 = 100 paise), so floats never touch the ledger.

A materializer turns each event into rows. This is also where the split happens:

// src/livestore/schema.ts (simplified)
'v1.ExpenseCreated': ({ id, amountMinor, participants, ...rest }) => [
  tables.expenses.insert({ id, amountMinor, participants, ...rest }).onConflict('id', 'ignore'),
  ...splitEqually(amountMinor, participants).map((share) =>
    tables.expenseShares.insert({ id: `${id}:${share.memberId}`, expenseId: id, ...share }),
  ),
],

splitEqually gives any leftover paise to participants in a fixed order. So ₹100.00 split three ways is always 3,334 + 3,333 + 3,333 paise, on every device that replays the same events.

The dashboard reads those tables through reactive queries. A component subscribes with store.useQuery(query$), and when a commit touches a table, LiveStore re-runs only the queries that depend on it. Only those components re-render.


Saving an expense is one line:

store.commit(events.expenseCreated({ id, title, category, amountMinor, paidBy, participants, createdAt: Date.now(), isSeed: false }))

The bug LiveStore had on a fresh install

The very first launch on a clean emulator crashed with this:

TypeError: importing from an existing database is not yet supported in expo

On first boot, LiveStore passes a database object to the Expo adapter's import(), which only accepts raw bytes. The fix is four lines: export the database to bytes first. It's applied with patch-package, so it survives npm install.

Two smaller setup notes: LiveStore's nanoid dependency needs a Metro resolver rule and a crypto polyfill, and Windows builds fail if the project path contains a &.

Adding Monitoring with Measure.sh

Measure ships an Expo config plugin. The API keys come from environment variables, so they never end up in the repo:

// app.config.ts
plugins: [
  ['@measuresh/react-native', {
    androidApiKey: process.env.MEASURE_ANDROID_API_KEY,
    androidApiUrl: process.env.MEASURE_ANDROID_API_URL,
  }],
],

Then one call when the app starts:

await Measure.init({ config: new MeasureConfig({ enableLogging: __DEV__ }) })

What gets tracked

Spans. The app has seven custom spans. Each one wraps something the app actually does, like a commit call, a query or a render, rather than guessing at LiveStore's internal timings.

Span What it measures
livestore_initialization App start until the store is ready (SQLite open, state loaded)
expense_commit A store.commit() call to add, edit, delete or settle
expense_query Running the dashboard queries in one query mode
balance_calculation Turning query rows into balances and settlements
reactive_update Just before a commit until the dashboard shows the new data
dataset_generation One full run of the test data generator
sync_recovery Sync dropping and then reconnecting

reactive_update matters most. It's the delay a user actually feels between tapping Save and seeing the numbers change.

One detail is easy to miss: spans started before Measure.init() finishes are silently dropped. The trace helper works around this by recording its own timestamps and sending the span with startSpanWithTimestamp once the SDK is ready. Without that, livestore_initialization never shows up at all.

Events. A few custom events round it out:

Event Sent when
expense_created An expense is added
expense_updated An expense is edited
expense_deleted An expense is deleted
dataset_generated The test data generator finishes
benchmark_completed A benchmark run finishes
query_mode_changed The query mode switches between optimized and unoptimized
sync_completed Pending events finish syncing
sync_failed The sync connection drops

They carry things like category, counts, durations and query mode. Never amounts.

A privacy filter. Every attribute goes through one function before it reaches Measure. It keeps only plain values, trims strings to Measure's 256-character limit, and drops any key that looks sensitive, even if one gets passed by mistake:

// src/instrumentation/attributes.ts (simplified)
const BLOCKED_KEY = /(amount|price|cost|total_minor|title|description|name|email|phone|note)/i

Handled errors. These are sent with the message swapped for a category like [commit_failed], because error messages can contain SQL values or user input. The stack trace stays.

Testing on an Android emulator

All tests ran on a debug build on an Android 12 (API 31) emulator, starting with seven Goa Trip expenses.

1. Reactive updates

A new expense went in: ₹777.77 for drinks, paid by Kabir. The total, the expense count, all four balances, the settlement suggestions and the category bar all updated from that one commit. The expense_commit span took 67.7 ms.

2. A larger dataset

The developer panel can generate test data, and the same size always gives the same expenses. It commits events in batches of 250. Each store.commit({ skipRefresh: true }, ...batch) is one SQLite transaction, with a single store.manualRefresh() at the end.

1,000 events took 28.5 s in total. Only 5.9 s of that was spent inside commit, and the final refresh took 13.9 ms. The other ~22 s went by between batches, while the UI caught up. The likely cause is LiveStore saving the eventlog on the JS thread, though that wasn't confirmed. Either way, commit time alone makes bulk writes on React Native look cheaper than they really are.

3. Optimized vs unoptimized queries

This is the most interesting part. The app can build the dashboard in two ways, and the mode can be switched while it's running.

Unoptimized is a pattern that shows up in plenty of real apps. It subscribes to every expense row, including deleted ones and the JSON participants column. Then it works out the total, categories, splits and balances in JavaScript, and sorts the whole list just to show 20 rows.

Optimized uses four focused queries and lets SQLite do the math on indexed columns. One query returns everything the balances need:

SELECT 'paid' AS kind, paidBy AS memberId, SUM(amountMinor) AS amountMinor
  FROM expenses WHERE deletedAt IS NULL GROUP BY paidBy
UNION ALL
SELECT 'owed', memberId, SUM(shareMinor) FROM expense_shares GROUP BY memberId
UNION ALL …

Both modes feed the same ledger functions, so they have to land on the same numbers. The benchmark checks this: it compares a fingerprint of both results and only shows Results identical if they match. The optimized SQL was also run against node:sqlite at 100, 1,000 and 10,000 rows. The results matched every time, and EXPLAIN QUERY PLAN showed the indexes being used for every sum.

The surprising result: saving got 6.5× slower in unoptimized mode, even though the write itself is exactly the same. In LiveStore, commit refreshes every subscribed query before it returns. So a heavy subscription slows down every save, not just every read.

Normal use in unoptimized mode told the same story. Adding and deleting an expense gave reactive_update spans of 461 ms and 577 ms. In optimized mode, the same actions took about 21 ms.

These numbers come from a handful of runs on one emulator with a debug build, so treat them as a comparison, not a benchmark. The README explains how to repeat the test on a release build.

Debugging with Claude Code and the Measure MCP server

Measure's MCP server lets an agent look at sessions, traces, errors and metrics directly. Setting it up is one command:

claude mcp add --transport http measure https://agent.measure.sh/mcp

The prompt given to Claude Code:

Test Measure MCP against the app. Check that Measure is not tracking internal
LiveStore data and only sees in-app data. Then give me an analysis, and tell me
what Measure MCP returned and how you found the issues.

How it worked

Claude Code started by creating some data to look for. It tapped through the emulator with adb and added an expense titled CANARYTITLE9431 for ₹777.77, two values that should never show up in Measure. Then it generated 1,000 events, ran the benchmark, switched to unoptimized mode, added and deleted an expense, and triggered a handled error. Putting the app in the background made Measure upload everything.

Then it queried Measure:

  • list_apps found SplitSync by its bundle ID.
  • get_sessions returned the two sessions from the run.
  • get_root_span_names listed all seven custom spans, plus Measure's own Activity TTID and Fragment TTID screen-load spans.
  • get_session returned every raw event: 181 in the main session and 71 in the unoptimized one.

The session data was 316 KB, which is a lot to read through. So Claude Code wrote a short script that counted events by type and searched everything for 25 strings: the canary title and amount, member names, SQL keywords, LiveStore table and event names, and the localhost ports.

The app's own telemetry came back clean. Events and spans only had the allowed attributes, like duration_ms, query_mode and expense_count, and nothing from LiveStore's internals showed up.

Measure's automatic tap tracking added useful context on top of that. Each gesture_click event includes the visible text of whatever was tapped as its label, which makes a session easy to follow:

{ "target": "ReactViewGroup", "label": "Late-night pizza #997" }
{ "target": "ReactViewGroup", "label": "KA" }

Those are an expense title and a member's initials. In most apps that's exactly the context you'd want. In a finance app, it's better to keep titles out. Claude Code looked into the measure-android SDK to see how labels are picked: it's the first TextView text inside the tapped view. That made the change easy. Rows now render their text as plain views, with an invisible Pressable on top:

<View style={styles.row}>
  <Pressable accessibilityLabel="Expense" onPress={() => onEdit(expense.id)} style={StyleSheet.absoluteFill} />
  {/* icon, title, payer, amount */}
</View>

The next MCP check found zero titles, amounts or names, and navigation still shows up through screen_view events.

If you want to build something like this, try LiveStore for the offline-first data layer and Measure.sh to see what's happening inside your app. You can check out the full SplitSync demo and run it yourself on GitHub.


If you love my content ❤️ Follow me on LinkedIn

~ Kathank Raithatha

Chat with me