Skip to content
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

add defaultServerValue property #74

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,44 @@ function useIsServerRender() {

</details>

<details>
<summary>Preventing hydration errors when server default value should be different from client default value</summary>
<p></p>

Using the `defaultValue` property to differ between server and client default values will cause hydration errors. To prevent them you can use the `defaultServerValue` property.

```tsx
// this will throw hydration error
const [state, setState] = useLocalStorageState(
'key',
{
defaultValue() {
if (isServer) {
return "server default value";
}
return "client default value";
},
},
);
```

`defaultServerValue` will overwrite `defaultValue` in the `useSyncExternalStore()` hook's `getSnapshot()` function.
Difference is server's `getSnapshot()` will run on server and client's hydration, then `defaultValue` or local storage value will be used after that.

```tsx
const [state, setState] = useLocalStorageState(
'key',
{
defaultValue: "client default value",
defaultServerValue: "server default value",
},
);
```

> Example use cases: You want to show a modal when the user's first enter and you are persistently storing that data on `localStorage`. Using `defaultServerValue` will allow you to show the modal only on the server.

</details>

## API

#### `useLocalStorageState(key: string, options?: LocalStorageOptions)`
Expand All @@ -165,6 +203,14 @@ Default: `undefined`

The default value. You can think of it as the same as `useState(defaultValue)`.

#### `options.defaultServerValue`

Type: `any`

Default: `undefined`

The default value for the server if it should be different from the client's default value. Server will use `defaultValue` if `defaultServerValue` is not provided.

#### `options.storageSync`

Type: `boolean`
Expand Down
6 changes: 5 additions & 1 deletion src/useLocalStorageState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export const inMemoryData = new Map<string, unknown>()

export type LocalStorageOptions<T> = {
defaultValue?: T | (() => T)
defaultServerValue?: T | (() => T)
storageSync?: boolean
serializer?: {
stringify: (value: unknown) => string
Expand Down Expand Up @@ -42,9 +43,11 @@ export default function useLocalStorageState<T = undefined>(
): LocalStorageState<T | undefined> {
const serializer = options?.serializer
const [defaultValue] = useState(options?.defaultValue)
const [defaultServerValue] = useState(options?.defaultServerValue)
return useLocalStorage(
key,
defaultValue,
defaultServerValue,
options?.storageSync,
serializer?.parse,
serializer?.stringify,
Expand All @@ -54,6 +57,7 @@ export default function useLocalStorageState<T = undefined>(
function useLocalStorage<T>(
key: string,
defaultValue: T | undefined,
defaultServerValue: T | undefined,
storageSync: boolean = true,
parse: (value: string) => unknown = parseJSON,
stringify: (value: unknown) => string = JSON.stringify,
Expand Down Expand Up @@ -125,7 +129,7 @@ function useLocalStorage<T>(
},

// useSyncExternalStore.getServerSnapshot
() => defaultValue,
() => defaultServerValue ?? defaultValue,
)
const setState = useCallback(
(newValue: SetStateAction<T | undefined>): void => {
Expand Down
24 changes: 23 additions & 1 deletion test/browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,34 @@ describe('useLocalStorageState()', () => {
expect(todos).toStrictEqual(['first', 'second'])
})

test(`initial state is written to localStorage`, () => {
test('initial state is written to localStorage', () => {
renderHook(() => useLocalStorageState('todos', { defaultValue: ['first', 'second'] }))

expect(localStorage.getItem('todos')).toStrictEqual(JSON.stringify(['first', 'second']))
})

test('should return defaultValue instead of defaultServerValue on the browser', () => {
const { result } = renderHook(() =>
useLocalStorageState('todos', {
defaultValue: ['first', 'second'],
defaultServerValue: ['third', 'forth'],
}),
)

const [todos] = result.current
expect(todos).toStrictEqual(['first', 'second'])
})

test('defaultServerValue should not written to localStorage', () => {
renderHook(() =>
useLocalStorageState('todos', {
defaultServerValue: ['third', 'forth'],
}),
)

expect(localStorage.getItem('todos')).toStrictEqual(null)
})

test('updates state', () => {
const { result } = renderHook(() =>
useLocalStorageState('todos', { defaultValue: ['first', 'second'] }),
Expand Down
29 changes: 27 additions & 2 deletions test/server.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,38 @@ describe('useLocalStorageState()', () => {
}),
)

expect(result.current[0]).toEqual(['first', 'second'])
const [todos] = result.current
expect(todos).toStrictEqual(['first', 'second'])
})

test('returns default value on the server', () => {
const { result } = renderHookOnServer(() => useLocalStorageState('todos'))

expect(result.current[0]).toEqual(undefined)
const [todos] = result.current
expect(todos).toBe(undefined)
})

test('returns defaultServerValue on the server', () => {
const { result } = renderHookOnServer(() =>
useLocalStorageState('todos', {
defaultServerValue: ['third', 'forth'],
}),
)

const [todos] = result.current
expect(todos).toStrictEqual(['third', 'forth'])
})

test('defaultServerValue should overwrite defaultValue on the server', () => {
const { result } = renderHookOnServer(() =>
useLocalStorageState('todos', {
defaultValue: ['first', 'second'],
defaultServerValue: ['third', 'forth'],
}),
)

const [todos] = result.current
expect(todos).toStrictEqual(['third', 'forth'])
})

test(`setValue() on server doesn't throw`, () => {
Expand Down
Loading