react-use icon indicating copy to clipboard operation
react-use copied to clipboard

New hook: createGlobalPersistedState - persisted version of createGlobalState ?

Open oguzgelal opened this issue 3 years ago • 0 comments

Thanks to libraries like react-query and swr I don't need full-fledged state management libraries anymore. But every now and then I'll end up needing to set a global variable or two, and createGlobalState is the perfect light-weight replacement for me. Only thing that stopped me from switching fully to it was the lack of persistence. IMO it would be cool if there was a hook that did that.

I ended up hacking createGlobalState like below:

const createGlobalPersistedState = <S = any>(
  persistorKey: string,
  defaultState: IHookStateInitAction<S>
): (() => [S, (state: IHookStateSetAction<S>) => void]) => {
  const hydrated = isServer ? null : storage.getSync<S>(persistorKey)
  const globalState = createGlobalState<S>(hydrated ?? defaultState)

  return () => {
    const [globalVal, globalValSet] = globalState()
    const globalValCustomSetter = useCallback(
      (setTo: IHookStateSetAction<S>) => {
        storage.setSync(persistorKey, setTo)
        globalValSet(setTo)
      },
      [globalValSet, storage.setSync]
    )

    return [globalVal, globalValCustomSetter]
  }
}

// ...
const useDebugMode = createGlobalPersistedState("debug", false)

// ...
const [debugMode, debugModeSet] = useDebugMode()

oguzgelal avatar Oct 19 '22 08:10 oguzgelal