ammarahm-ed / react-native-mmkv-storage

An ultra fast (0.0002s read/write), small & encrypted mobile key-value storage framework for React Native written in C++ using JSI
https://rnmmkv.now.sh
MIT License
1.58k stars 109 forks source link

App wide access to storage #273

Closed dcassese closed 9 months ago

dcassese commented 2 years ago

I can't seem to figure out the best way to access my mmkv instance from other screens and files in my app? Do I use context? What's recommend way to do this. I create my instance in app.js but need to write to it from various Functional components.

douugdev commented 2 years ago

You don't need to create MMKV instances inside components, you can load MMKV at a global scope, such as in the docs:

import { MMKVLoader, useMMKVStorage } from 'react-native-mmkv-storage';

const storage = new MMKVLoader().initialize();

const App = () => {
  const [user, setUser] = useMMKVStorage('user', storage, 'robert');
  const [age, setAge] = useMMKVStorage('age', storage, 24);

  return (
    <View style={styles.header}>
      <Text style={styles.headerText}>
        I am {user} and I am {age} years old.
      </Text>
    </View>
  );
};

just be careful as you need to use hooks such as useMMKVStorage inside components (as per the rules of hooks)


I usually create a separate file to hold such instance:

// storage.ts

const storage = new MMKVLoader().initialize();
export default storage;