https://github.com/leoafarias/use-state-persist
Simple React Hook to persist/cache the useState locally. Easily load stale state for better ux.
https://github.com/leoafarias/use-state-persist
asyncstorage hooks localstorage persistent react-hooks usestate
Last synced: about 2 months ago
JSON representation
Simple React Hook to persist/cache the useState locally. Easily load stale state for better ux.
- Host: GitHub
- URL: https://github.com/leoafarias/use-state-persist
- Owner: leoafarias
- License: mit
- Created: 2020-05-23T21:37:47.000Z (about 5 years ago)
- Default Branch: master
- Last Pushed: 2022-07-18T13:11:11.000Z (almost 3 years ago)
- Last Synced: 2024-10-20T10:51:19.079Z (8 months ago)
- Topics: asyncstorage, hooks, localstorage, persistent, react-hooks, usestate
- Language: TypeScript
- Homepage:
- Size: 420 KB
- Stars: 52
- Watchers: 6
- Forks: 5
- Open Issues: 8
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Use State Persist
 [](https://coveralls.io/github/leoafarias/use-state-persist?branch=master) [](https://app.codacy.com/manual/leo/use-state-persist?utm_source=github.com&utm_medium=referral&utm_content=leoafarias/use-state-persist&utm_campaign=Badge_Grade_Dashboard) [](https://www.npmjs.com/package/use-state-persist)
A simple React Hook to persist **useState** in local storage.
Works on the `Web` and `React Native`.
**Easily implement**
- Offline state
- Stale while revalidate flow
- Global state```bash
npm install use-state-persist
# or
yarn add use-state-persist
```For `React Native` make sure you do the following on app start up:
```typescript
import { syncStorage } from 'use-state-persist';// Initialize async storage
await syncStorage.init();
```## How to persists useState
Same behavior and API as `useState` so you can use it by easily replacing the `useState` hook for the calls which you want to persist offline.
```tsx
import { useStatePersist as useState } from 'use-state-persist';const Component = () => {
// Before
//const [counter, setCounter] = useState(0);
const [counter, setCounter] = useState('@counter', 0);return ;
};
```## Stale While Revalidate
```tsx
import { useStatePersist as useState } from 'use-state-persist';const Component = () => {
// Loads stale state
const [data, setData] = useState('@data');const fetchData = async () => {
// Fetches new state
const data = await fetch('/endpoint');
setData(data);
};useEffect(() => {
fetchData();
}, []);return ;
};
```## Global State
Simple event system allows all the storage writes to be dispatched to all hooks . That means that all `useStatePersist()` can be used as a global state by sharing the same key `useStatePersist('@globalKey')`
To avoid that just make sure that the key being passed to the hook is unique `useStatePersist('@uniqueKey')`
```tsx
const CounterButton = () => {
const [counter, setCounter] = useState('@counter');return setCounter(counter => counter++)} />;
};
```State will be updated across multiple components
```tsx
const ShowCounter = () => {
const [counter, setCounter] = useState('@counter', 0);return ;
};
```## Cache Invalidation
There are some cases where you might want to clear all the local storage cache for the hook, pending a certain change in state in the app.
This will clear all the local storage items use by the `useStatePersist` hook when the key changes.
### Use Cases
- User/App State changes
- User Log out
- Environment variable changes```tsx
import { invalidateCache } from 'use-state-persist';invalidateCache('CACHE_KEY');
// You can also send a promise which will compare the result
invalidateCache(async () => 'CACHE_KEY');
```### React Native
Init prepares the SyncStorage to work synchronously, by getting all values for all keys stored on AsyncStorage. You can use the init method on the web without any side effects to keep code consistency.
```typescript
import { syncStorage } from 'use-state-persist';await syncStorage.init();
```