Skip to content

[useLocalStorageState] Add getInitialValueInEffect option to avoid SSR hydration mismatches #2856

@kondo0602

Description

@kondo0602

Problem

When using useLocalStorageState in an SSR framework, the server cannot access localStorage, so the server render uses the defaultValue. On the client, however, the initial render may immediately read a different value from localStorage.

If that value affects the rendered HTML structure, the server-generated markup and the client markup diverge, causing a hydration warning/error.

Example: defaultValue is false but localStorage contains true, and that value toggles a switch UI between on/off.

Proposal

Add a boolean option getInitialValueInEffect. When true, the hook should:

Render the initial value without reading localStorage during the first render (SSR-safe).

After mount, read from localStorage inside an effect and update the state.

This defers the localStorage read to the client effect phase and prevents hydration mismatches.

function ExampleToggle() {
  const [enabled, setEnabled] = useLocalStorageState<boolean>('feature-x', {
    defaultValue: false,
    getInitialValueInEffect: true,
  });

  return (
    <label>
      <input
        type="checkbox"
        checked={!!enabled}
        onChange={(e) => setEnabled(e.target.checked)}
      />
      Enable feature X
    </label>
  );
}

This avoids hydration errors even if localStorage.getItem('feature-x') === 'true'.

Prior Art

Mantine’s useLocalStorage exposes the same idea via a getInitialValueInEffect option, and it has worked well in SSR contexts.

https://v6.mantine.dev/hooks/use-local-storage/#definition

Would you accept a PR?

If this direction sounds good, I’d be happy to open a PR implementing getInitialValueInEffect.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions