Created
September 20, 2021 09:26
-
-
Save mathdroid/e43bc4ddf82971a733d7fc925c75eea6 to your computer and use it in GitHub Desktop.
useCachedState
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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