Last active
March 3, 2022 19:42
-
-
Save nihlton/f23443246209bd2d52fa552ac7caf34f to your computer and use it in GitHub Desktop.
useLocalStorage React Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useCallback, useEffect } from 'react' | |
const customEvent = 'myMagicalStorageHook' | |
export default function useLocalStorage( | |
key, | |
initialValue, | |
lifeSpan = Infinity | |
) { | |
const [storedValue, setStoredValue] = useState(() => { | |
try { | |
const item = window.localStorage.getItem(key) | |
const stampedValue = JSON.parse(item) | |
const JSONValue = | |
stampedValue && | |
stampedValue.expire > Date.now() && | |
JSON.parse(stampedValue.JSONValue) | |
return JSONValue || initialValue | |
} catch (error) { | |
return initialValue | |
} | |
}) | |
const setValue = useCallback( | |
(value) => { | |
try { | |
const expire = Date.now() + lifeSpan | |
const JSONValue = JSON.stringify(value) | |
const stampedValue = { expire, JSONValue } | |
window.dispatchEvent( | |
new CustomEvent(customEvent, { detail: { key, value } }) | |
) | |
setStoredValue(value) | |
window.localStorage.setItem(key, JSON.stringify(stampedValue)) | |
} catch (error) { | |
console.log(error) | |
} | |
}, | |
[key, lifeSpan] | |
) | |
useEffect(() => { | |
const listener = window.addEventListener(customEvent, (event) => { | |
const keyMatch = event.detail.key === key | |
const newValue = event.detail.value !== storedValue | |
if (keyMatch && newValue) { | |
setStoredValue(event.detail.value) | |
} | |
}) | |
return window.removeEventListener(customEvent, listener) | |
}, [key, storedValue]) | |
return [storedValue, setValue] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
pretty standard hook - except that it accepts a life span in milliseconds. after the life span elapses, the initial value will be returned.