Created
October 31, 2020 09:22
-
-
Save Infi-Knight/54aaec6fb0cfcae1c4919b55a4dfe34e to your computer and use it in GitHub Desktop.
React hook to sync component state with local storage
This file contains hidden or 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 React, {useState, useRef, useEffect} from 'react' | |
| export const useLocalStorageState = ( | |
| key, | |
| defaultValue = '', | |
| {serialize = JSON.stringify, deserialize = JSON.parse} = {} | |
| ) => { | |
| const [state, setState] = useState(() => { | |
| const valueInLocalStorage = window.localStorage.getItem(key) | |
| if (valueInLocalStorage){ | |
| return deserialize(valueInLocalStorage) | |
| } | |
| return typeof defaultValue === 'function' ? defaultValue() : defaultValue; | |
| }) | |
| const prevKeyRef = useRef(key) | |
| useEffect(() => { | |
| const prevKey = prevKeyRef.current | |
| if (prevKey !== key) { | |
| window.localStorage.removeItem(key) | |
| } | |
| prevKeyRef.current = key | |
| window.localStorage.setItem(key, serialize(state)) | |
| }, [key, state, serialize]) | |
| return [state, setState] | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment