Skip to content

Instantly share code, notes, and snippets.

@hongkheng
Created June 10, 2020 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongkheng/f1895822f57958280d8a3535e1e830ba to your computer and use it in GitHub Desktop.
Save hongkheng/f1895822f57958280d8a3535e1e830ba to your computer and use it in GitHub Desktop.
import { useState, useEffect } from 'react'
export const useLocalStorage = (key, value = undefined) => {
const [storeValue, setStoreValue] = useState(() => {
// get value if exists in localStorage
const item = window.localStorage.getItem(key)
return item
})
useEffect(() => {
window.localStorage.setItem(key, value)
}, [key, value])
return {
storeValue,
setStoreValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment