> Complete content index: https://narsil.sondelali.com/llms.txt

# React Native

> Search an index that an iOS or Android app stores on the phone, so that search works offline and the index stays on the phone after the app closes.

URL: https://narsil.sondelali.com/docs/react-native
Section: Clients
Version: 0.4 (@delali/narsil@0.4.3, latest)

`@delali/narsil-react-native` puts a Narsil engine inside an iOS or Android app, so that the app can search its documents by keyword, by vector, or by both while the phone is offline. The engine takes the same settings as on Node.js, so you can pass an embedding adapter, a plugin, or an id generator to `createNarsil` directly. Each method takes the same arguments as the method of the same name on the [Indexes and documents](/docs/indexes-and-documents) page, while every method returns a promise. By default, the engine writes each index to files in the app's private storage, so the index stays on the phone after the user closes the app.

On this page, you'll build a trip-notes screen in `trip-notes.ts` and `TripNotesScreen.tsx`, and then add a backup to a file. Because the site builds these pages on a computer with no phone attached, this page shows no output panels, and the text describes what the app shows. The same calls, made against `@delali/narsil` 0.4.1 on Node.js, return the results that the text describes, while the TypeScript compiler accepts the code against `@delali/narsil-react-native` 0.4.1.

## What the app needs

The package contains native code that compiles the C search core for iOS and for 64-bit Android, so it works only in an app build that includes that code. Expo Go and every build for a 32-bit Android phone leave that code out, so in both cases `createNarsil` rejects with `NATIVE_DEPENDENCY_MISSING`. The app also needs React Native's New Architecture and `react-native-nitro-modules`, which lets JavaScript call the native code. `@delali/narsil-react-native` 0.4.1 declares `@delali/narsil` 0.4.1 as a peer dependency, so install the two at the same version.

## Set up an Expo app

Install the packages with Expo's installer:

```bash
npx expo install @delali/narsil@0.4.1 @delali/narsil-react-native@0.4.1 react-native-nitro-modules
```

Add the config plugin to `app.json`. The plugin sets `reactNativeArchitectures` to `arm64-v8a,x86_64` in the Android build, because the native module has no 32-bit library:

```json title="app.json"
{
  "expo": {
    "plugins": ["@delali/narsil-react-native"]
  }
}
```

Then make a development build with `npx expo run:ios` or `npx expo run:android`. You can leave your Babel and Metro settings as they are. The plugin accepts one option, `keep32BitAndroid: true`, which leaves the Android architectures as the app sets them, so `createNarsil` rejects with `NATIVE_DEPENDENCY_MISSING` on a 32-bit build of that app.

## Set up an app without Expo

Install the packages in the app:

```bash pm
pnpm add -E @delali/narsil@0.4.1 @delali/narsil-react-native@0.4.1 react-native-nitro-modules
```

Set the Android architectures in `android/gradle.properties`, since no Expo plugin sets them for you:

```properties title="android/gradle.properties"
reactNativeArchitectures=arm64-v8a,x86_64
```

Install the pods with `pod install` in the `ios` folder, and then rebuild the app for each platform. You can leave your Babel and Metro settings as they are.

## Open the index once and search it

Start the engine once for the whole app, because each call to `createNarsil` starts another engine. `openTripNotes` keeps the promise of the first start, so every screen that searches waits on the same engine. When the start fails, `openTripNotes` clears the promise so that the next call can try again. The engine replays the write-ahead log of each index when it starts, so `listIndexes` returns `trip-notes` on every launch after the first one, which is why `startTripNotes` creates the index only when the list lacks it.

```ts title="trip-notes.ts"
import { createNarsil, type PhoneNarsil } from '@delali/narsil-react-native'

export interface TripNoteHit {
  id: string
  title: string
}

let opening: Promise<PhoneNarsil> | undefined

const startTripNotes = async (): Promise<PhoneNarsil> => {
  const narsil = await createNarsil()
  const indexes = await narsil.listIndexes()
  if (!indexes.some((index) => index.name === 'trip-notes')) {
    await narsil.createIndex('trip-notes', { schema: { title: 'string', body: 'string' }, language: 'english' })
  }
  return narsil
}

export const openTripNotes = (): Promise<PhoneNarsil> => {
  opening ??= startTripNotes().catch((error: unknown) => {
    opening = undefined
    throw error
  })
  return opening
}

export const saveTripNote = async (id: string, title: string, body: string): Promise<void> => {
  const narsil = await openTripNotes()
  if (await narsil.has('trip-notes', id)) {
    await narsil.update('trip-notes', id, { title, body })
  } else {
    await narsil.insert('trip-notes', { title, body }, id)
  }
}

export const searchTripNotes = async (term: string): Promise<TripNoteHit[]> => {
  const narsil = await openTripNotes()
  const found = await narsil.query<{ title: string }>('trip-notes', {
    term,
    limit: 10,
    document: { include: ['title'] },
  })
  return found.hits.map((hit) => ({ id: hit.id, title: hit.document?.title ?? '' }))
}
```

`saveTripNote` writes a note under an id that you choose, so a second save under the same id replaces the title and body of the first. Suppose that the app saves three notes, 'Pack the tent poles', 'Ferry from Split to Hvar', and 'Rail pass for Kyoto', whose bodies are about pegs, tickets at the port, and the first train. A search for `tent` then returns the tent-poles note, a search for `tickets ferry` returns the ferry note, and a search for `trains` returns the rail-pass note, because the English stemmer reduces 'trains' and 'train' to the same stem.

## Search as somebody types

`TripNotesScreen` sends a search each time the text in the box changes, and then it shows the titles of the hits in a list. The effect discards the answer to any search that finishes after a later keystroke, because its cleanup sets `isCurrent` to `false`, so a slow search for `fer` can't replace the hits for `ferry`.

```tsx title="TripNotesScreen.tsx"
import { type ReactElement, useCallback, useEffect, useState } from 'react'
import { FlatList, type ListRenderItemInfo, Text, TextInput, View } from 'react-native'
import { searchTripNotes, type TripNoteHit } from './trip-notes'

export const TripNotesScreen = (): ReactElement => {
  const [term, setTerm] = useState('')
  const [hits, setHits] = useState<TripNoteHit[]>([])
  const [failure, setFailure] = useState<string | null>(null)

  useEffect(() => {
    if (term.trim().length === 0) {
      setHits([])
      return
    }
    let isCurrent = true
    searchTripNotes(term).then(
      (found) => {
        if (isCurrent) {
          setHits(found)
          setFailure(null)
        }
      },
      (error: unknown) => {
        if (isCurrent) setFailure(error instanceof Error ? error.message : String(error))
      }
    )
    return () => {
      isCurrent = false
    }
  }, [term])

  const renderHit = useCallback(({ item }: ListRenderItemInfo<TripNoteHit>): ReactElement => <Text>{item.title}</Text>, [])
  const keyOfHit = useCallback((item: TripNoteHit): string => item.id, [])

  return (
    <View>
      <TextInput value={term} onChangeText={setTerm} placeholder="Search your trip notes" />
      {failure !== null && <Text>{failure}</Text>}
      <FlatList data={hits} renderItem={renderHit} keyExtractor={keyOfHit} />
    </View>
  )
}
```

The engine keeps its slow work off the JS thread, so that the app can keep drawing the screen while a search or an import is under way. The engine sends file reads, file writes, file syncs, and each vector search to native threads, while it yields the JS thread to the app between the steps of a long import or search.

## Where the engine keeps the index

`createNarsil()` turns on a write-ahead log in a `narsil` directory inside the app's private storage, which is `Library/Application Support` on iOS and the app's files directory on Android. The engine syncs each write to that log before the write resolves, so a write that resolves stays on the phone after the app closes or the system ends it. On iOS, the engine syncs each file with `F_FULLFSYNC`, which also makes the drive write its cache to storage.

Pass another `directory` in `durability` to keep the files somewhere else, as in `createNarsil({ durability: { directory: 'search' } })`. A relative path resolves against the app's private storage, while an absolute path stays as it is. Pass `durability: null` to keep every index in memory, in which case the app loses every index when it closes. Every other durability setting works as the [Persistence and durability](/docs/persistence-and-durability) page describes.

## Back up the index to a file

`snapshot` resolves with the bytes of one `.nrsl` file, while `restore` takes those bytes back, so a server can restore a phone's snapshot and a phone can restore a server's. For an index that is too large to hold twice in memory, pass a file path in place of the bytes. `snapshotToFile` writes the snapshot to a file and resolves with its size in bytes, while `restoreFromFile` reads a snapshot from a file one MiB at a time. In the step below, you add both to `trip-notes.ts`.

```ts title="trip-notes.ts"
import { createNarsil, type PhoneNarsil } from '@delali/narsil-react-native' // [!code --]
import { createNarsil, isNarsilError, type PhoneNarsil } from '@delali/narsil-react-native' // [!code ++]

export interface TripNoteHit {
  id: string
  title: string
}

let opening: Promise<PhoneNarsil> | undefined

const startTripNotes = async (): Promise<PhoneNarsil> => {
  const narsil = await createNarsil()
  const indexes = await narsil.listIndexes()
  if (!indexes.some((index) => index.name === 'trip-notes')) {
    await narsil.createIndex('trip-notes', { schema: { title: 'string', body: 'string' }, language: 'english' })
  }
  return narsil
}

export const openTripNotes = (): Promise<PhoneNarsil> => {
  opening ??= startTripNotes().catch((error: unknown) => {
    opening = undefined
    throw error
  })
  return opening
}

export const saveTripNote = async (id: string, title: string, body: string): Promise<void> => {
  const narsil = await openTripNotes()
  if (await narsil.has('trip-notes', id)) {
    await narsil.update('trip-notes', id, { title, body })
  } else {
    await narsil.insert('trip-notes', { title, body }, id)
  }
}

export const searchTripNotes = async (term: string): Promise<TripNoteHit[]> => {
  const narsil = await openTripNotes()
  const found = await narsil.query<{ title: string }>('trip-notes', {
    term,
    limit: 10,
    document: { include: ['title'] },
  })
  return found.hits.map((hit) => ({ id: hit.id, title: hit.document?.title ?? '' }))
}

const TRIP_NOTES_BACKUP = 'trip-notes.nrsl' // [!code ++:17]

export const backUpTripNotes = async (): Promise<number> => {
  const narsil = await openTripNotes()
  return narsil.snapshotToFile('trip-notes', TRIP_NOTES_BACKUP)
}

export const restoreTripNotes = async (): Promise<boolean> => {
  const narsil = await openTripNotes()
  try {
    await narsil.restoreFromFile('trip-notes', TRIP_NOTES_BACKUP)
    return true
  } catch (error: unknown) {
    if (isNarsilError(error) && error.code === 'PERSISTENCE_LOAD_FAILED') return false
    throw error
  }
}
```

A relative path resolves against the app's private storage, in the same way as the durability directory. The package writes only into a folder that already exists, so keep the backup at the top of the private storage, or use a folder that the app creates first. `snapshotToFile` writes to a temporary file first and renames it once every byte is on storage, so a backup that fails part of the way through leaves the earlier backup in place.

`restoreFromFile` replaces the index of the same name with the contents of the file, while a failed restore leaves the index unchanged. When the bytes of a file differ from the bytes that `snapshotToFile` writes, `restoreFromFile` fails with `PERSISTENCE_LOAD_FAILED`, which `restoreTripNotes` turns into `false` so that the screen can tell the user that the backup is damaged. `isNarsilError` returns true for any error that holds one of the engine's codes, which the [Errors](/docs/errors) page lists, while `restoreTripNotes` passes every other failure, such as a missing file, on to its caller. `exportDocumentsToFile` and `importDocumentExportFromFile` do the same for a document export.

## Keep the engine's JavaScript off the app's thread

An app whose JavaScript keeps the JS thread busy can move the engine's JavaScript to a separate Hermes runtime. `createNarsil` from `@delali/narsil-react-native/worklets` starts the engine on a [Worklets](https://docs.swmansion.com/react-native-worklets/) runtime and returns the same client, so the only change to `trip-notes.ts` is its import. An app that never imports that entry point bundles none of its code and needs no Worklets install.

That runtime makes inserts slower, because the client copies each batch across to the engine's runtime before the engine can index it. The [Narsil React Native guide](https://github.com/assetcorp/narsil/blob/narsil-ts%40v0.4.1/docs/react-native.md) records measurements on a physical Android phone and a physical iPhone. In those measurements, an insert of 10,000 documents into memory takes 6% to 13% longer than on the app's JS runtime on the Android phone and 7% to 12% longer on the iPhone. In a larger comparison, an insert of 50,000 documents with a write-ahead log takes 22% longer on the Android phone and 32% longer on the iPhone, while the longest pause that a 10 ms timer on the app's JS thread measures during that insert falls from 111 ms to 30 ms on the Android phone and from 144 ms to 74 ms on the iPhone. An import from a file sends only the file's path across, so in the same measurements it takes between 0% and 18% longer.

The runtime loads the package's code through Worklets Bundle Mode, so the app needs `react-native-worklets`, Bundle Mode turned on in its Babel settings, and a wrapped Metro config:

```bash pm
pnpm add -E react-native-worklets
```

In an Expo app, turn Bundle Mode on in `babel.config.js` and forward the package's source to the engine's runtime, and then wrap Expo's Metro config in `metro.config.js`:

<CodeGroup defaultTab="babel.config.js">

```js title="babel.config.js"
module.exports = (api) => {
  api.cache(true)
  return {
    presets: [['babel-preset-expo', { worklets: false }]],
    plugins: [
      [
        'react-native-worklets/plugin',
        {
          bundleMode: true,
          strictGlobal: true,
          importForwarding: { relativePaths: ['@delali/narsil-react-native/src'] },
        },
      ],
    ],
  }
}
```

```js title="metro.config.js"
const { getDefaultConfig } = require('expo/metro-config')
const { getBundleModeMetroConfig } = require('react-native-worklets/bundleMode')

module.exports = getBundleModeMetroConfig(getDefaultConfig(__dirname))
```

</CodeGroup>

In an app without Expo, add the same plugin to the React Native preset in `babel.config.js`, and then wrap the React Native Metro config in `metro.config.js`:

<CodeGroup defaultTab="babel.config.js">

```js title="babel.config.js"
module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: [
    [
      'react-native-worklets/plugin',
      {
        bundleMode: true,
        strictGlobal: true,
        importForwarding: { relativePaths: ['@delali/narsil-react-native/src'] },
      },
    ],
  ],
}
```

```js title="metro.config.js"
const { getDefaultConfig } = require('@react-native/metro-config')
const { getBundleModeMetroConfig } = require('react-native-worklets/bundleMode')

module.exports = getBundleModeMetroConfig(getDefaultConfig(__dirname))
```

</CodeGroup>

Bundle Mode writes each worklet to a new file while Metro builds the bundle, so Metro can stop with `Failed to get the SHA-1` when one of those files is missing from its index. In the [Bundle Mode setup guide](https://docs.swmansion.com/react-native-worklets/docs/bundleMode/setup/), Software Mansion recommends a patch that makes Metro index those files as Bundle Mode writes them, with a link to the instructions for that patch.

The client sends each setting to the engine's runtime as data, so the worklets entry point drops every setting that holds a function, such as `embeddingAdapters`, `plugins`, and `idGenerator`. Pass those through the second argument of `createNarsil`, a function that starts with the `'worklet'` directive. That function executes on the engine's runtime before the engine starts, and it returns the settings that hold functions. Register a language module or a tokenizer inside that function too, because the engine's runtime holds a separate copy of each module. `createNarsil` rejects with a `TypeError` when the second argument lacks the directive.

## When the phone is low on memory

The operating system ends an app that uses too much memory, so the engine refuses, with `MEMORY_WRITE_BLOCKED`, any insert or update that can take the app past its limit. On iOS the engine adds the memory that `os_proc_available_memory()` reports to the app's footprint to find the limit. On Android it counts the app's anonymous and shared resident memory and adds the available memory that `ActivityManager` reports, less its low-memory threshold. The engine still accepts removals, searches, and reads while it blocks writes, as the section [Refuse writes before memory fills up](/docs/observability#refuse-writes-before-memory-fills-up) describes, so `saveTripNote` can fail with that code while `searchTripNotes` keeps returning hits.

## Where to go next

- Read [Device sync](/docs/device-sync) for how the phone can keep a copy of one user's index from a server and upload its writes once it reconnects.
- Read [Vector search](/docs/vector-search) for how the engine ranks notes by meaning through a vector field, which works on the phone with an embedding adapter.
- Read [Persistence and durability](/docs/persistence-and-durability) for the write-ahead log and its settings.
- Read [Errors](/docs/errors) for every code that the error of a rejected call can hold.
