Files
Compass/web/hooks/use-persistent-local-state.ts
MartinBraquet 0a9b08803e Add comment
2025-11-08 18:48:47 +01:00

34 lines
1.3 KiB
TypeScript

import { safeJsonParse } from 'common/util/json'
import { useEffect } from 'react'
import { safeLocalStorage } from 'web/lib/util/local'
import { isFunction } from 'web/hooks/use-persistent-in-memory-state'
import { useStateCheckEquality } from 'web/hooks/use-state-check-equality'
import { useEvent } from 'web/hooks/use-event'
import { useIsClient } from 'web/hooks/use-is-client'
export const usePersistentLocalState = <T>(initialValue: T, key: string) => {
// Note: use a version (like "-v1") in the key to increment after backwards-incompatible changes
const isClient = useIsClient()
const [state, setState] = useStateCheckEquality<T>(
(isClient && safeJsonParse(safeLocalStorage?.getItem(key))) || initialValue
)
const saveState = useEvent((newState: T | ((prevState: T) => T)) => {
setState((prevState: T) => {
const updatedState = isFunction(newState) ? newState(prevState) : newState
safeLocalStorage?.setItem(key, JSON.stringify(updatedState))
return updatedState
})
})
useEffect(() => {
if (safeLocalStorage) {
const storedJson = safeJsonParse(safeLocalStorage.getItem(key))
const storedValue = storedJson ?? initialValue
if (storedJson === null && initialValue === undefined) return
saveState(storedValue as T)
}
}, [key])
return [state, saveState] as const
}