useSyncedLocalStorage (React)

Save state to localStorage and sync it between components, custom hooks, tabs and windows! It also has an almost identical interface to useState.

This is an extended & more 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.

However, it comes with the cost of being larger, doing more work, and having a dependency.

typescriptjavascript
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 localStorage
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 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 | null
 
type 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]
}
import { useEffect, useRef, useState } from 'react'
import mitt from 'mitt'
 
const em = mitt()
 
// Store which keys are tracked so we don't do unnecessary work for other uses of localStorage
const trackedKeys = {}
 
// 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 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 ?? '')
      } 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 = (key, initialValue) => {
  const [state, setState] = useState(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))
    } catch (err) {
      setState(initialValueRef.current)
    }
  }, [key])
 
  useEffect(() => {
    const handler = data => {
      // 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]
}

Info

  • This hook relies on the mitt event emitter package - it's 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.

Warning

  • The type of the state that you use this hook with cannot be nullable (i.e. cannot be null or undefined) - and must be something that can be serialised as JSON (you can't used things like Set or Map). 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

Created 07/07/22Updated 30/08/23
Found a mistake, or want to suggest an improvement? Source on GitHub here
and see edit history here