useLocalStorage (React)
Save to localStorage
whenever state changes and read form it for the first
render.
typescriptjavascript
import type { Dispatch, SetStateAction } from 'react'import { useCallback, useEffect, useState } from 'react'const useLocalStorage = <T>( key: string, initialValue: T): [get: T, set: Dispatch<SetStateAction<T>>, clear: () => void] => { const [state, setState] = useState<T>(() => { const cached = localStorage.getItem(key) if (!cached) return initialValue try { return JSON.parse(cached) as T } catch (err) { return initialValue } }) useEffect(() => { localStorage.setItem(key, JSON.stringify(state)) }, [state, key]) const clearState = useCallback(() => { setState(initialValue) }, [initialValue]) return [state, setState, clearState]}
Info
- We use
useCallback
for theclearState
function to prevent unnecessary re-renders if you use theclearState
function inside auseEffect
oruseCallback
and list it in the dependency array.
Warning
- This version of the hook with only work client-side and will throw an error you server-render a component using the hook
- You should only run the hook once per key at a time - the hook doesn't handle
changes when another instance of the hook updates the matching key in
localStorage
. If you do want to handle that, check outuseSyncedLocalStorage
Usage
tsxjsx
const Example = () => { const [input, setInput] = useLocalStorage('example:input', '') return ( <> <input value={input} onChange={e => setInput(e.target.value)} /> </> )}
Demo
Watch the value for the example:input
key in the
Application > Local Storage
section in your devtools as you type in the input.
If you're on mobile, enter some text into the input, and reload the page - when
you do, you'll see the same text that you entered pre-filled.
License & Attribution
Attribution
You should place the following attribution (and probably the license below it) above your copy of the code, but 🤷♂️.
This snippet "useLocalStorage (React)" from "https://soorria.com/snippets/use-local-storage"
was created by Soorria Saruva (https://soorria.com) and is covered under the
MIT license found here: https://github.com/soorria/soorria.com/blob/master/LICENSE.
License
If you want, you can (and probably should) include the entire license below. I'm not a lawyer, though so idrk.
MIT License Copyright (c) 2022 Soorria Saruva Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.