useSyncedLocalStorage (React)
Save state to localStorage and sync it between hook instances, tabs and windows!
It also has an almost identical interface to useState
.
This is an extended / advanced version of
useLocalStorage
that adds the following
features:
- SSR / SSG support (defaults to
initialValue
on the server, and on initial render to prevent react's hydration warnings) - Synchronisation of state for
key
acrossuseSyncedLocalStorage
instances in the same / different tabs and between windows of the same app.
import type { Dispatch, SetStateAction } from 'react'import { useEffect, useRef, useState } from 'react'import mitt from 'mitt'const em = mitt<Record<string, any>>()// Store which keys are tracked so we don't do unnecessary work for other uses of localStorageconst trackedKeys: Record<string, number> = {}// This block relies on window, so to make sure it only runs on the client// we need to icheck if `window` is definedif (typeof window !== 'undefined') { // We define this globally since it simplifies the already extremely // complicated hook a tiny bit, and we can handle it all in one event handler window.addEventListener('storage', event => { if ( // the `storage` event also fires for `sessonStorage`, and we don't care about that for this hook event.storageArea === localStorage && // Intentionally using `!=` instead of `!==` since it checks `null` and `undefined` event.key != null && trackedKeys[event.key] ) { let parsed try { parsed = JSON.parse(event.newValue ?? '') as unknown } catch { parsed = null } em.emit(event.key, event.newValue == null ? null : parsed) } }) // Same as above - we can handle setting localStorage all in one spot. em.on('*', (key, data) => { localStorage.setItem(key, JSON.stringify(data)) })}type JsonValue = NonNullJsonValue | nulltype NonNullJsonValue = | string | number | boolean | { [key: string]: JsonValue } | JsonValue[]export const useSyncedLocalStorage = < T extends NonNullJsonValue = NonNullJsonValue>( key: string, initialValue: T): [T, Dispatch<SetStateAction<T>>] => { const [state, setState] = useState<T>(initialValue) const initialised = useRef(false) const shouldSync = useRef(false) const emitting = useRef(false) const initialValueRef = useRef(initialValue) useEffect(() => { initialValueRef.current = initialValue }, [initialValue]) useEffect(() => { trackedKeys[key] = (trackedKeys[key] ?? 0) + 1 return () => { trackedKeys[key]-- } }, [key]) useEffect(() => { if (initialised.current) return initialised.current = true const cached = localStorage.getItem(key) if (!cached) { setState(initialValueRef.current) return } try { setState(JSON.parse(cached) as T) } catch (err) { setState(initialValueRef.current) } }, [key]) useEffect(() => { const handler = (data: T | null) => { // If this hook is the one that sent the message, just ignore it if (!emitting.current) { shouldSync.current = false setState(data ?? initialValueRef.current) } } em.on(key, handler) return () => { em.off(key, handler) } }, [key]) useEffect(() => { // Prevents this hook from re-sending an update if (!shouldSync.current) { shouldSync.current = true return } // Prevents this hook from setting itself again emitting.current = true em.emit(key, state) emitting.current = false }, [state, key]) return [state, setState]}
Warning
-
The type of the
state
that you use this hook with cannot be nullable (i.e. cannot benull
orundefined
) - and must be something that can be serialised as JSON (you can't used things likeSet
orMap
). This is enforced in the type signature of the hook so if you're using TypeScript, issues should be caught at compile-time. If you do want the value to be nullable, I recommend wrapping your state in an object (e.g.useSyncedLocalStorage<{ user: User | null }>('user', { user: null })
), or you can modify the hook to suit your needs. -
Unfortunately we have 4 refs of which none are used for DOM elements, and I'm not sure of a better way to get around the issues they solve without adding extra state
License & Attribution
Attribution
You should place the following attribution (and probably the license below it) above your copy of the code, but 🤷♂️.
This snippet "useSyncedLocalStorage (React)" from "https://soorria.com/snippets/use-synced-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.