react-native-use-persisted-state
v1.0.2
Published
Simple persisted state in react-native
Downloads
33
Maintainers
Readme
React Native Use Persisted State
Preview
Introduce
💾 Simple persisted state in react-native
🌏 Globally accessable like redux, recoil...
🚀 No loading, Immediate synchronization
Usage
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>
);
};
Getting started
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
Second, Pod intsall
cd ios && pod install
Third, Add provider
// App.js
...
import {PersistedStateProvider} from 'react-native-use-persisted-state' // here
const App = () => {
return (
<PersistedStateProvider> // here
<.../>
</PersistedStateProvider> // here
);
};
API
usePersistedState
Params
usePersistedState<T>(key, initialState);
| name | type | require | default | description |
| ------------ | -------- | ------- | ----------- | ------------------------- |
| key | string
| ✅ | | key used to store storage |
| initialState | T
| | undefined
| |
Returns
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
|