-
Notifications
You must be signed in to change notification settings - Fork 5
feat: add use-local-storage-state #62
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Debbl
wants to merge
3
commits into
main
Choose a base branch
from
feat/use-local-storage-state
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| # useLocalStorageState | ||
|
|
||
| Persist state in `localStorage` with SSR-safe snapshots and automatic same-tab / cross-tab synchronization. | ||
|
|
||
| ## Usage | ||
|
|
||
| ```tsx | ||
| import { useLocalStorageState } from '@/hooks/use-local-storage-state' | ||
|
|
||
| function Component() { | ||
| const [theme, setTheme, removeTheme] = useLocalStorageState('theme', 'light') | ||
|
|
||
| return ( | ||
| <div> | ||
| <p>Theme: {theme}</p> | ||
| <button onClick={() => setTheme('dark')}>Dark</button> | ||
| <button | ||
| onClick={() => setTheme((prev) => (prev === 'dark' ? 'light' : 'dark'))} | ||
| > | ||
| Toggle | ||
| </button> | ||
| <button onClick={removeTheme}>Reset</button> | ||
| </div> | ||
| ) | ||
| } | ||
| ``` | ||
|
|
||
| ## Type Declarations | ||
|
|
||
| ```ts | ||
| import type { Dispatch, SetStateAction } from 'react' | ||
|
|
||
| export interface UseLocalStorageStateOptions<T> { | ||
| serializer?: (value: T) => string | ||
| deserializer?: (value: string) => T | ||
| onError?: (error: unknown) => void | ||
| } | ||
|
|
||
| export type UseLocalStorageStateReturn<T> = [ | ||
| T, | ||
| Dispatch<SetStateAction<T>>, | ||
| () => void, | ||
| ] | ||
|
|
||
| export function useLocalStorageState<T>( | ||
| key: string, | ||
| initialValue: T | (() => T), | ||
| options?: UseLocalStorageStateOptions<T>, | ||
| ): UseLocalStorageStateReturn<T> | ||
| ``` | ||
|
|
||
| ## Parameters | ||
|
|
||
| | Parameter | Type | Default | Description | | ||
| | -------------- | -------------------------------- | ------- | --------------------------------------------------------- | | ||
| | `key` | `string` | - | The `localStorage` key | | ||
| | `initialValue` | `T \| (() => T)` | - | Fallback value during SSR or when storage value is absent | | ||
| | `options` | `UseLocalStorageStateOptions<T>` | `{}` | Serializer, deserializer, and optional error callback | | ||
|
|
||
| ## Returns | ||
|
|
||
| | Type | Description | | ||
| | -------------------------------- | ---------------------------------------------------- | | ||
| | `[value, setValue, removeValue]` | Current value, React-style updater, and clear method | |
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| 'use client' | ||
| import { useState } from 'react' | ||
| import { Button } from '~/components/ui/button' | ||
| import { | ||
| Card, | ||
| CardContent, | ||
| CardDescription, | ||
| CardHeader, | ||
| CardTitle, | ||
| } from '~/components/ui/card' | ||
| import { Input } from '~/components/ui/input' | ||
| import { useHash } from '..' | ||
|
|
||
| const PRESET_HASHES = ['intro', 'api', 'faq'] | ||
|
|
||
| export function Demo01() { | ||
| const hash = useHash() | ||
| const [inputValue, setInputValue] = useState('demo-hash') | ||
|
|
||
| const setHash = (value: string) => { | ||
| const nextHash = value ? `#${value}` : '' | ||
| window.location.assign( | ||
| `${window.location.pathname}${window.location.search}${nextHash}`, | ||
| ) | ||
| } | ||
|
|
||
| return ( | ||
| <Card className='shadow-none ring-0'> | ||
| <CardHeader> | ||
| <CardTitle>useHash Demo</CardTitle> | ||
| <CardDescription> | ||
| Update the URL hash and watch the hook value change in real time. | ||
| </CardDescription> | ||
| </CardHeader> | ||
| <CardContent className='space-y-4'> | ||
| <Input | ||
| value={inputValue} | ||
| onChange={(event) => setInputValue(event.target.value)} | ||
| placeholder='Type hash without #' | ||
| /> | ||
Debbl marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| <div className='flex flex-wrap items-center gap-2'> | ||
| <Button type='button' onClick={() => setHash(inputValue)}> | ||
| Set hash | ||
| </Button> | ||
| <Button type='button' variant='outline' onClick={() => setHash('')}> | ||
| Clear hash | ||
| </Button> | ||
| </div> | ||
|
|
||
| <div className='flex flex-wrap items-center gap-2'> | ||
| {PRESET_HASHES.map((item) => ( | ||
| <Button | ||
| key={item} | ||
| type='button' | ||
| variant='secondary' | ||
| onClick={() => setHash(item)} | ||
| > | ||
| #{item} | ||
| </Button> | ||
| ))} | ||
| </div> | ||
|
|
||
| <p className='text-muted-foreground text-sm'> | ||
| Current hash:{' '} | ||
| <span className='text-foreground font-mono'>{hash}</span> | ||
| </p> | ||
| </CardContent> | ||
| </Card> | ||
| ) | ||
| } | ||
This file contains hidden or 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
42 changes: 42 additions & 0 deletions
42
src/registry/hooks/use-local-storage-state/demo/demo-01.tsx
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| 'use client' | ||
| import { Button } from '~/components/ui/button' | ||
| import { Input } from '~/components/ui/input' | ||
| import { useLocalStorageState } from '..' | ||
|
|
||
| const DEMO_STORAGE_KEY = 'shadcn-hooks:demo:use-local-storage-state' | ||
|
|
||
| export function Demo01() { | ||
| const [name, setName, clearName] = useLocalStorageState<string>( | ||
| DEMO_STORAGE_KEY, | ||
| '', | ||
| ) | ||
|
|
||
| return ( | ||
| <div className='space-y-4'> | ||
| <div className='space-y-2'> | ||
| <label htmlFor='local-storage-name' className='text-sm font-medium'> | ||
| Persisted name | ||
| </label> | ||
| <Input | ||
| id='local-storage-name' | ||
| value={name} | ||
| onChange={(event) => setName(event.target.value)} | ||
| placeholder='Type and refresh the page' | ||
| /> | ||
| </div> | ||
|
|
||
| <div className='flex items-center gap-2'> | ||
| <Button type='button' variant='outline' onClick={() => setName('demo')}> | ||
| Fill sample | ||
| </Button> | ||
| <Button type='button' variant='destructive' onClick={clearName}> | ||
| Clear | ||
| </Button> | ||
| </div> | ||
|
|
||
| <p className='text-muted-foreground text-sm'> | ||
| Current value: <span className='font-mono'>{name || '(empty)'}</span> | ||
| </p> | ||
| </div> | ||
| ) | ||
| } |
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| --- | ||
| title: useLocalStorageState | ||
| description: A hook to persist state in localStorage with SSR-safe behavior | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix article in description text. Line 3 should read “An SSR-safe...” instead of “A SSR-safe...”. 🤖 Prompt for AI Agents |
||
| --- | ||
|
|
||
| import { Demo01 } from './demo/demo-01' | ||
|
|
||
| <Demo01 /> | ||
|
|
||
| ## Installation | ||
|
|
||
| <Tabs items={['CLI', 'Manual']}> | ||
| <Tab> | ||
| <InstallCLI value='use-local-storage-state' /> | ||
| </Tab> | ||
| <Tab> | ||
| Copy and paste the following code into your project. | ||
| <RegistrySourceCode value='use-local-storage-state' /> | ||
| </Tab> | ||
| </Tabs> | ||
|
|
||
| ## API | ||
|
|
||
| ```ts | ||
| import type { Dispatch, SetStateAction } from 'react' | ||
|
|
||
| export interface UseLocalStorageStateOptions<T> { | ||
| serializer?: (value: T) => string | ||
| deserializer?: (value: string) => T | ||
| onError?: (error: unknown) => void | ||
| } | ||
|
|
||
| export type UseLocalStorageStateReturn<T> = [ | ||
| T, | ||
| Dispatch<SetStateAction<T>>, | ||
| () => void, | ||
| ] | ||
|
|
||
| /** | ||
| * A SSR-safe localStorage state hook with same-tab and cross-tab synchronization. | ||
| * | ||
| * @param key - localStorage key | ||
| * @param initialValue - Initial state value, used during SSR and when key does not exist | ||
| * @param options - Optional serializer, deserializer, and error callback | ||
| * @returns [state, setState, removeState] | ||
| */ | ||
| export function useLocalStorageState<T>( | ||
| key: string, | ||
| initialValue: T | (() => T), | ||
| options?: UseLocalStorageStateOptions<T>, | ||
| ): UseLocalStorageStateReturn<T> | ||
| ``` | ||
|
|
||
| ## Credits | ||
|
|
||
| - [useSyncExternalStore](https://react.dev/reference/react/useSyncExternalStore) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Normalize user input before building the hash fragment.
If users type a leading
#, Line 21 prepends another one and creates##...in the URL fragment. Strip leading hashes (and whitespace) first.Proposed fix
const setHash = (value: string) => { - const nextHash = value ? `#${value}` : '' + const normalized = value.trim().replace(/^#+/, '') + const nextHash = normalized ? `#${normalized}` : '' window.location.assign( `${window.location.pathname}${window.location.search}${nextHash}`, ) }📝 Committable suggestion
🤖 Prompt for AI Agents