Use parsers to validate your local/session storage
Create an object mapping every key to appear in localStorage to a Zod schema:
import { useLocalStorage } from 'use-valid-storage'
import { z } from 'zod'
// Usage
export default function Component() {
const [isDarkTheme, setDarkTheme] = useLocalStorage('darkTheme', true, {
schema: z.boolean(),
})
const toggleTheme = () => {
setDarkTheme((prevValue: boolean) => !prevValue)
}
return (
<button onClick={toggleTheme}>
{`The current theme is ${isDarkTheme ? `dark` : `light`}`}
</button>
)
}
Credit to trpc from where I got the parser utils. Great library btw.