Skip to content

KoreanThinker/react-native-use-persisted-state

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

17 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

React Native Use Persisted State

npm version npm download License MIT

Stars Twitter

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