๐พ Simple persisted state in react-native
๐ Globally accessable like redux, recoil...
๐ No loading, Immediate synchronization
import {View, Text, Button} from 'react-native';
import {usePersistedState} from 'react-native-use-persisted-state';
const Counter = () => {
const [count, setCount] = usePersistedState('@count', 0);
return (
<View>
<Text>count : {count}</Text>
<Button onPress={() => setCount(count + 1)} title="increment" />
<Button onPress={() => setCount(count - 1)} title="decrement" />
</View>
);
};
First, Install react-native-use-persisted-state
& @react-native-async-storage/async-storage
yarn add react-native-use-persisted-state @react-native-async-storage/async-storage
cd ios && pod install
// App.js
...
import {PersistedStateProvider} from 'react-native-use-persisted-state' // here
const App = () => {
return (
<PersistedStateProvider> // here
<.../>
</PersistedStateProvider> // here
);
};
usePersistedState<T>(key, initialState);
name | type | require | default | description |
---|---|---|---|---|
key | string |
โ | key used to store storage | |
initialState | T |
undefined |
const [state, setState, clear] = usePersistedState<T>(...);
name | type | description |
---|---|---|
state | T |
same as react state const [state] = useState() |
setState | (v:T) => void |
same as react setState const [..., setState] = useState() |
clear | () => void |
clear storage and init state to initialState |