Using SQLite in Expo for Offline React Native Apps

Forbes Lindesay
ITNEXT
5 min readFeb 24, 2020

--

One of the biggest things that determines whether an app “feels” native is how fast it is. A lot of making an app feel fast is about optimising key hot code paths and having the right animations, but for most apps there will be at least some parts of the app that involve reading and writing data.

Whilst it is becoming rarer for a user to be fully offline, it’s still really common for mobile users in particular to have poor network connectivity. If you want your app to feel fast when the network is slow, you’ll need at least some aspects of your app to work offline.

For the sake of this article I’m going to assume you’re using Expo. If you’re not familiar with Expo, it’s a great way to build native apps for iOS and Android using react-native. It basically saves you from all the pain of setting up an environment to build native apps and lets you get straight to writing JavaScript/TypeScript.

So your app needs to store data, but it also needs to work (at least partially) offline. This means you need a way to store some of that data locally. If you want to avoid compiling native modules (and leaving the expo ecosystem) you have 3 basic options:

  1. SecureStore
  2. AsyncStorage
  3. SQLite

Secure Store

expo-secure-store provides a way to encrypt and securely store key–value pairs locally on the device

If you need to store any kind of secret keys. e.g. the user’s authentication token for your API, Secure Store is the only sensible option. This is the only option that ensures your data is encrypted at rest, but it’s also only appropriate for fairly small amounts of data. If you need to encrypt larger amounts of data, you could store and encryption key in SecureStore.

import * as SecureStore from 'expo-secure-store';await SecureStore.setItemAsync('token', 'my-token-value');const myToken = await SecureStore.getItemAsync('token');

In my experience on iOS it is possible for this to throw an exception if the device hasn’t quite finished unlocking when your app requests the token. It…

--

--

JavaScript enthusiast and maintainer of many open source projects.