A basic understanding of JavaScript and familiarity with React/React Native will be required to understand how to use libraries and configure your React Native application to persist data.

When building React Native applications, there are several ways to persist data, with each having its own strong advantage. In this piece, we shall discuss the most popular ways to persist data in our React Native application.

React Native lets you build mobile apps using only JavaScript. It uses the same design as React, which allows you to build the mobile UIs as components.

Prerequisites

A basic understanding of JavaScript and familiarity with React/React Native will be required to understand how to use libraries and configure your React Native application to persist data.

Methods of persisting data in React Native

React Native provides methods to persist data. Some are provided out of the box while others are libraries you have to install and use. Below are popular methods of persisting data in React Native

AsyncStorage

React Native SQLite 2

Realm

React Native Local MongoDB

AsyncStorage

According to the official React Native docs, this is the most recommended way to persist data in your React Native applications as it is already built into React Native.

AsyncStorage functions like the HTML5 local storage class and it uses key-value pairs to persist data.

Data saved using the Asyncstorage class are usually not permanent on the device and are usually not encrypted, therefor when using this method, you must provide your backup and synchronization classes.

Do not use AsyncStorage if you'll be dealing with a large amount of data in your application.

Security

AsyncStorage encrypts none of the data saved. All objects are stored as strings and must be serialized before they can be saved and likewise be de-serialized before retrieval.

Usage

Import the AsyncStorage library:

import { AsyncStorage } from "react-native";

To persist data:

// create a function that saves your data asyncronously _storeData = async () => { try { await AsyncStorage.setItem('name', 'John'); } catch (error) { // Error saving data } }

To fetch persisted data:

// fetch the data back asyncronously _retrieveData = async () => { try { const value = await AsyncStorage.getItem('name'); if (value !== null) { // Our data is fetched successfully console.log(value); } } catch (error) { // Error retrieving data } }

React Native SQLite 2

This is a plugin which provides a WebSQL API to persist data. It provides SQL-like syntax, for querying your in-app persisted database.

It has support for both Android, iOS, and windows. It's also considered being a drop-in replacement with react-native-sqlite-storage .

Security

SQLite doesn't support encryption out of the box, but with an extension named SQLite Encryption Extension (SEE) which is provided on their official website. SEE allows SQLite to read/write data in an encrypted format using algorithms like AES-128, AES-256, RC4, and so on.

Aside from SEE, there are other extensions that allow an encryption to be possible such as SQLCipher.

Usage

To get started, install react-native-sqlite-2:

$ npm install react-native-sqlite-2 --save

Link the library dependency:

$ react-native link react-native-sqlite-2

Import the library and persist data:

import SQLite from 'react-native-sqlite-2';

Open the database file:

const db = SQLite.openDatabase('test.db', '1.0', '', 1);

Create a transaction function to execute your SQL statements:

db.transaction(function (txn) { // Drop the table if it exists txn.executeSql('DROP TABLE IF EXISTS Users', []); // Create the table and define the properties of the columns txn.executeSql('CREATE TABLE IF NOT EXISTS Users(user_id INTEGER PRIMARY KEY NOT NULL, name VARCHAR(30))', []); // Insert a record txn.executeSql('INSERT INTO Users (name) VALUES (:name)', ['nora']); // Insert another record txn.executeSql('INSERT INTO Users (name) VALUES (:name)', ['takuya']); // Select all inserted records, loop over them while printing them on the console. txn.executeSql('SELECT * FROM `users`', [], function (tx, res) { for (let i = 0; i < res.rows.length; ++i) { console.log('item:', res.rows.item(i)); } }); });

Realm

Realm was designed and built from scratch to support mobile devices and even wearables. It's designed as an object-oriented database and this makes it up to 10x faster than SQLite. It's simple to use since it exposes data as objects and it supports relationships among data, mapping classes, tables, foreign keys and so on.

Realm can be combined with server-side databases to allow seamless synchronization of data offline to the cloud/server database. Realm is a fantastic choice if you'll be dealing with large data in your application.

Security

Realm is dynamic with the way it encrypts data. It uses different encryption mechanism for different mobile platform. For Android, Realm uses the AES-256 level of encryption and decryption of all the data stored locally. For iOS applications, Realm's encryption is based on the iOS CommonCrypto library. The library protects the application data and passwords stored in the keychain. While for Windows applications, Realm uses Crypto library for encryption.

Usage

To get started with realm in React Native:

$ npm install realm --save

Link the library dependency:

$ react-native link realm

Import the library:

const Realm = require('realm');

Initiate the realm state to null:

constructor(props) { super(props); this.state = { realm: null }; }

Persist data:

// Write it into the realm state as soon as the component mounts componentWillMount() { // Open a Realm Schema Realm.open({ schema: [{name: 'Dog', properties: {name: 'string'}}] }).then(realm => { // Write a record into the realm schema realm.write(() => { realm.create('Dog', {name: 'Rex'}); }); // Update the realm state this.setState({ realm }); }); }

Fetch and render:

render() { const info = this.state.realm ? 'Number of dogs in this Realm: ' + this.state.realm.objects('Dog').length: 'Loading...'; return ( <View style={styles.container}></View> <Text style={styles.welcome}> {info} </Text> </View> ); }

Putting it together as a component:

// import the library const Realm = require('realm'); class RealmDb extends Component { //initiate the realm state to null constructor(props) { super(props); this.state = { realm: null }; } //persist data and write it into the realm state as soon as the component mounts componentWillMount() { // Open a Realm Schema Realm.open({ schema: [{name: 'Dog', properties: {name: 'string'}}] }).then(realm => { // Write a record into the realm schema realm.write(() => { realm.create('Dog', {name: 'Rex'}); }); // Update the realm state this.setState({ realm }); }); } // render a Text component with the value render() { const info = this.state.realm ? 'Number of dogs in this Realm: ' + this.state.realm.objects('Dog').length: 'Loading...'; return ( <View style={styles.container}></View> <Text style={styles.welcome}> {info} </Text> </View> ); } }

React Native Local MongoDB

MongoDB is an open-source server-side database built for scalability and complex applications and Big data. It uses key-value stores and a relational database to store data as objects in JSON documents.

MongoDB can read and write JavaScript objects and allows smooth communication between the server and app. It's a right choice if you'll be dealing with large data in your application.

However, MongoDB can be slow for connected models that require joins.

Security

MongoDB supports encryption directly out of the box, unlike SQLite. According to the official docs on encryption, It uses the MongoDB’s Encrypted Storage Engine, which supports a variety of encryption algorithms from the OpenSSL library. AES-256 in CBC mode is the default, while other options include GCM mode and FIPS mode for FIPS-140-2 compliance. It also uses the SCRAM-SHA-1 algorithm mechanism for authentication and a role-based access control.

Usage

To get started with using MongoDB in your React Native application:

$ npm install react-native-local-mongodb --save

Create a datastore:

var Datastore = require('react-native-local-mongodb'), db = new Datastore({ filename: 'asyncStorageKey', autoload: true });

Insert into your database:

db.insert([{ a: 5 }, { a: 42 }], function (err, newDocs) { // Two documents were inserted in the database });

Find a document:

db.find({ system: 'solar' }, function (err, docs) { // docs is an array containing documents Mars, Earth, Jupiter // If no document is found, docs is equal to [] });

Update a document:

db.update({ planet: 'Jupiter' }, { planet: 'Pluton'}, {}, function (err, numReplaced) { // numReplaced = 1 // The doc #3 has been replaced by { _id: 'id3', planet: 'Pluton' } // Note that the _id is kept unchanged, and the document has been replaced });

Remove a document:

db.remove({ _id: 'id2' }, {}, function (err, numRemoved) { // numRemoved = 1 });

Indexing:

db.ensureIndex({ fieldName: 'somefield' }, function (err) { // If there was an error, err is not null });

Conclusion

React Native provides several ways to persist data and your choice should depend on the type and amount of data you'll be handling. We have seen four methods of persisting data in React Native, each with its own strength. AsyncStorage is great for storing small data which needs to be serialized. You shouldn't use AsyncStorage for handling relational data in any form. If you are interested in storing relational data, look more into SQLite. If SQLite is too slow for what you want to achieve, then Realm is the better solution. If you are storing JavaScript objects to your database, then you should consider MongoDB.