Skip to content

Instantly share code, notes, and snippets.

@mathdroid
Created September 20, 2021 09:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathdroid/e43bc4ddf82971a733d7fc925c75eea6 to your computer and use it in GitHub Desktop.
Save mathdroid/e43bc4ddf82971a733d7fc925c75eea6 to your computer and use it in GitHub Desktop.
useCachedState
import useSWR, { Key, useSWRConfig } from 'swr'
import { useEffect } from 'react'
export const useCachedState = <T>(key: Key, fallbackData?: T) => {
/// cache is used for subsequent uses
const { cache } = useSWRConfig()
/// if initial data is empty, use value from cache
const initialData = fallbackData ?? cache.get(key)
const { data, mutate } = useSWR(key, {
fallbackData: initialData,
})
/// we mutate once to fill the fallbackData into cache
useEffect(() => {
void mutate(initialData, false)
}, [])
const setState = (newState: T) => {
void mutate(newState)
}
return [data, setState] as const
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment