Overview
TheuseHydrateState hook allows you to initialize or override store state values once when a component mounts. This is particularly useful for server-side rendering (SSR), Next.js, or when you need to populate store state from external sources like URL parameters, API responses, or props.
Signature
Parameters
Partial state object containing the values to hydrate. Only the provided keys will be updated in the store.
- Can include any writable properties from the store
- Readonly properties (computed getters) are ignored
- Values are applied via the store’s setter actions
- Updates are batched for optimal performance
Return Value
Void. The hook updates the store state as a side effect.Behavior
- Runs Once: Only executes on the first render (mount), never on re-renders
- Batched Updates: All state updates are batched using
batchUpdatesto trigger only one notification - Partial Updates: Only updates the keys provided, leaving other state unchanged
- Action-Based: Uses the store’s setter actions to update state, ensuring consistency
- Idempotent: Calling multiple times in the same component has no additional effect after the first call
Examples
Basic Hydration
SSR with Next.js
Hydration from URL Parameters
Hydration from API Response
Partial Hydration
Multiple Components Hydrating
With Computed Properties
Hydration with Storage
Conditional Hydration
Use Cases
- SSR/SSG: Hydrating client store with server-rendered data
- Route Parameters: Initializing filters/state from URL
- API Responses: Populating store from fetched data
- Props to Store: Converting component props to global state
- Draft Recovery: Restoring unsaved work from localStorage
- User Preferences: Loading saved settings on mount
- Deep Linking: Setting up app state from URL
Comparison with Direct Actions
useHydrateState:
- Runs once, guaranteed (not dependent on useEffect timing)
- Automatically batches all updates
- More concise and declarative
- No dependency array to manage
Type Safety
The hook only accepts writable properties:Performance
- Updates are batched using
batchUpdates, so subscribers are notified only once - Uses a ref to ensure the hydration logic runs only once, even with React Strict Mode
- Minimal overhead: no subscriptions or effects created
Notes
- Only runs once per component instance (uses
useRefinternally) - Works correctly with React Strict Mode (which mounts components twice in development)
- Does not re-run if the
stateparameter changes on re-renders - Computed properties (getters) cannot be hydrated
- Updates are synchronous and immediate
- Can be called in multiple components; each component’s hydration runs independently
- Calling with an empty object
{}is valid but has no effect