In this lesson, you will learn how to choose between the file system and keyed databases to persist data in your React Native applications.
When building for the web, you are often limited to localStorage, a simple key-value store that treats all data as strings. In React Native, you have much more power because you have direct access to the device's native storage systems. Understanding the difference between these two approaches is essential for managing your app's persistent state.
File System Storage
The file system allows you to store raw data as individual files. Think of this like a physical filing cabinet on your computer. You decide exactly where the file lives and what it’s named.
Use this approach when you are dealing with large binary data, such as images, videos, or documents that you have downloaded. Because you are interacting with the native file system, you can stream these files without loading the entire content into your JavaScript memory, which keeps your app running smoothly without UI jank.
Keyed Databases
A keyed database (or key-value store) is like a digital index card box. You store a piece of data associated with a specific "key," and you retrieve it by asking for that key.
Use this for structured, lightweight data like user preferences, authentication tokens, or app settings. Unlike a file system, databases are optimized to quickly find and update small snippets of info without you having to manually manage individual files.
Choosing the right tool
- Use File System Storage when you are handling large assets or binary blobs where you need to manage paths and file metadata.
- Use Keyed Databases when you have a large collection of small objects or settings that need to be read or written to frequently.
// Example: Storing a simple setting in a keyed database
await database.set('theme', 'dark');
// Example: Saving a large image file to the native file system
await fileSystem.save('user_avatar.jpg', imageBlob);
By choosing the right storage medium, you ensure your app is both performant and efficient with the device's storage resources.
Key Takeaway: Choose keyed databases for lightweight configuration and state, and use the file system for managing larger binary assets and documents.