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 across useSyncedLocalStorage instances in the same / different tabs and between windows of the same app.
typescriptjavascript
import type { Dispatch, SetStateAction } from 'react'
import { useEffect, useRef, useState } from 'react'
import mitt from 'mitt'
const em = mitt<Record<string, any>>()
const 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 defined
if (typeof window !== 'undefined') {
// We define this globally since it simplifies the already extremely
// complicated hook a tiny bit, and we can handle
window.addEventListener('storage', event => {
if (
event.storageArea === localStorage &&
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))
})
}
export const useSyncedLocalStorage = <
T extends NonNullable<any>,
K extends string
>(
key: K,
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]
}

Note:

  • This hook relies on the mitt event emitter package - it's only tiny at only 200 bytes(!!) that I would have had to include anyway (for syncing between hook instances in the same tab), and has tests that I don't want to write.

  • The type of the state that you use this hook with cannot be nullable (i.e. cannot be null or undefined). This is enforced in the type signature of the hook so if you're using TypeScript, issues should be caught at compile-time, 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

Created 07/07/22 • Updated 09/14/22
Found a mistake, or want to suggest an improvement? Edit on GitHub here
and see edit history here

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.