Selective persistence
Persist user preferences while keeping temporary UI state in memory.
Zustand · Pipe
partialize is a persist option that chooses which store fields are written to storage. Return a smaller object to keep selected state across reloads while excluding transient fields.
Within persist options, partialize receives the complete store state and returns the object that should be written to storage. Returning a smaller object allows selected fields to survive reloads while transient fields and actions remain runtime-only; omitting the option uses the entire state by default.
partialize: (state: Object) => Object| Name | Type | Description |
|---|---|---|
state | Object | The complete store state; the callback uses it to construct the persisted object. |
An object containing the subset of state fields to store; by default, the original state object is returned.
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
type Store = {
token: string
theme: 'light' | 'dark'
setToken: (token: string) => void
setTheme: (theme: Store['theme']) => void
}
export const useStore = create<Store>()(
persist(
(set) => ({
token: '',
theme: 'light',
setToken: (token) => set({ token }),
setTheme: (theme) => set({ theme }),
}),
{
name: 'app-storage',
partialize: (state) => ({ theme: state.theme }),
},
),
)Persists only the theme while leaving the token and action functions out of stored data.
Persist user preferences while keeping temporary UI state in memory.
Avoid writing credentials, caches, or other transient fields to storage.
Store only the fields needed to reconstruct a feature after reload.
partialize is a persist option typed as a function from an object state to an object. Its return value determines which state fields are stored, so returning { theme: state.theme } persists only that field.
Follow-up: What happens when the option is omitted? The identity function is used, so the complete state is selected for persistence.
Use partialize to return a new object containing only the fields that should be persisted. The other fields remain available in the live Zustand store but are excluded from the persisted representation.
Follow-up: How could you exclude several named fields? Build the returned object by filtering the state's entries, as shown in the documentation.
partialize belongs in the options object passed to persist, alongside settings such as the storage name. It receives the current state and returns the persisted subset.
Follow-up: What is the type of the option? (state: Object) => Object, with the identity function as its default.
persiststoragehydratecreateJSONStorage