1.0.2 ā€¢ Published 2 years ago

react-native-use-persisted-state v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

React Native Use Persisted State

npm version npm download License MIT PRs Welcome Stars

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);
nametyperequiredefaultdescription
keystringāœ…key used to store storage
initialStateTundefined

Returns

const [state, setState, clear] = usePersistedState<T>(...);
nametypedescription
stateTsame as react state const [state] = useState()
setState(v:T) => voidsame as react setState const [..., setState] = useState()
clear() => voidclear storage and init state to initialState