Last active
October 1, 2019 22:26
-
-
Save opensourcekam/3de4d925b9a96285f509ce799178118b to your computer and use it in GitHub Desktop.
use state with persistent storage
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, useEffect } from 'react'; | |
export const useStateLocalStorage = (localStorageKey, initialState = "") => { | |
const init = localStorage.getItem(localStorageKey) || initialState; | |
const [value, setValue] = useState(init); | |
useEffect(() => { | |
localStorage.setItem(localStorageKey, value); | |
}, [value]); | |
return [value, setValue]; | |
}; |
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, useEffect } from 'react'; | |
export const useStateSessionStorage = (localStorageKey, initialState = "") => { | |
const init = sessionStorage.getItem(localStorageKey) || initialState; | |
const [value, setValue] = useState(init); | |
useEffect(() => { | |
sessionStorage.setItem(localStorageKey, value); | |
}, [value]); | |
return [value, setValue]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment