Skip to content

Instantly share code, notes, and snippets.

@Chris927
Created April 30, 2020 13:37
Show Gist options
  • Save Chris927/4fdb13bd0a0ff18fde5a8d0122de137d to your computer and use it in GitHub Desktop.
Save Chris927/4fdb13bd0a0ff18fde5a8d0122de137d to your computer and use it in GitHub Desktop.
React Native, use persistent state via a hook
import React, { useState, useEffect } from 'react'
import { useAsyncStorage } from '@react-native-community/async-storage'
export default function usePersistedState(initialValue, { key }) {
if (!key) {
throw new Error('key is required');
}
const [localState, setLocalState] = useState(initialValue)
const { getItem, setItem } = useAsyncStorage('@' + key)
// load persisted state, if present
useEffect(() => {
getItem().then(value => {
// console.log('got value', value)
setLocalState(JSON.parse(value))
})
}, [])
useEffect(() => {
setItem(JSON.stringify(localState)) // is async
}, [localState])
return [localState, setLocalState]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment