Skip to content

Commit

Permalink
🐎 smaller bundle size — removes special condition when server-side re…
Browse files Browse the repository at this point in the history
…ndering
  • Loading branch information
astoilkov committed Jun 6, 2024
1 parent 247cc27 commit 81d2603
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 20 deletions.
22 changes: 2 additions & 20 deletions src/useLocalStorageState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,27 +40,8 @@ export default function useLocalStorageState<T = undefined>(
key: string,
options?: LocalStorageOptions<T | undefined>,
): LocalStorageState<T | undefined> {
const [defaultValue] = useState(options?.defaultValue)

// SSR support
// - on the server, return a constant value
// - this makes the implementation simpler and smaller because the `localStorage` object is
// `undefined` on the server
if (typeof window === 'undefined') {
return [
defaultValue,
(): void => {},
{
isPersistent: true,
removeItem: (): void => {},
},
]
}

const serializer = options?.serializer
// disabling ESLint because the above if statement can be executed only on the server. the value
// of `window` can't change between calls.
// eslint-disable-next-line react-hooks/rules-of-hooks
const [defaultValue] = useState(options?.defaultValue)
return useBrowserLocalStorageState(
key,
defaultValue,
Expand All @@ -84,6 +65,7 @@ function useBrowserLocalStorageState<T>(
})

const value = useSyncExternalStore(
// useSyncExternalStore.subscribe
useCallback(
(onStoreChange) => {
const onChange = (localKey: string): void => {
Expand Down
16 changes: 16 additions & 0 deletions test/server.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,21 @@ describe('useLocalStorageState()', () => {

expect(result.current[2].isPersistent).toBe(true)
})

test('can call mutation methods without throwing and without actually mutating the data', () => {
const { result } = renderHookOnServer(() => {
const hook = useLocalStorageState('number', {
defaultValue: 0,
})
const [, setValue, { removeItem }] = hook
setValue(1)
removeItem()
return hook
})
const hook = result.current

const [value] = hook
expect(value).toBe(0)
})
})
})

0 comments on commit 81d2603

Please sign in to comment.