Skip to content
WingoUI
ComponentsTemplatesDocsPricingAI agentsBlogChangelogContact
Components
Buttons & Actions
ButtonButton GroupCopy ButtonDelete ButtonTheme ToggleToggleToggle Group
Inputs
Avatar UploadCalendarCheckboxColor PickerComboboxCountry SelectCron PickerCurrency InputDate PickerDate Range PickerDate Time PickerDuration PickerEmail InputEmoji PickerFile UploadFilter BuilderInputInput GroupListboxMasked InputMention InputMonth PickerMulti SelectNumber InputOTP InputPassword InputPhone InputRadio GroupRatingSearch InputSegmented ControlSelectSignature PadSliderSwitchTag InputTextareaTime PickerTimezone SelectTree Select
Forms
Address InputBooking WidgetCSV ImportFieldForm WizardInline EditInvoice line itemsRich Text EditorSchema Builder
Navigation
Back To TopBounce SidebarBreadcrumbCommand MenuGlobal SearchGooey NavHook SidebarNav MenuNav TabsPaginationProximity SidebarScroll ProgressSidebarStepsTable Of ContentsTabsTopbarUser MenuWorkspace Switcher
Overlays
Alert DialogContext MenuDialogDrawerDropdown MenuFamily DrawerHover CardPopoverShare DialogSheetShortcuts DialogTooltipTour
Feedback
AlertBannerCookie ConsentEmoji ReactionEmpty StateNotification BellNotification CenterProgressRoute ProgressSetup ChecklistSkeletonSpinnerToast
Data Display
Approval FlowAvatarBadgeCalendar ViewCode BlockComment ThreadContact cardCountdownDescription ListDiff ViewerFile ListFile managerFolderGanttJSON ViewerKbdLog ViewerMarkdownPresenceSchedulerTagTimelineTree View
Tables & Lists
Audit LogData TableDeal PipelineEditable GridKanbanListMembers tablePermissions MatrixTableTask ListVirtual List
Charts & Stats
Animated CounterArea chartBar chartDonut chartFunnel chartGaugeGitHub ActivityHeatmap calendarLeaderboardLine chartRadar chartRadial barSparklineStat CardTrackerTrend badge
Layout
AccordionApp ShellCardCollapsibleDetail LayoutEntity HeaderPage HeaderScroll AreaSeparatorSettings LayoutSplit ViewToolbar
Media
Audio PlayerCarouselCSV ViewerDOCX EditorDOCX ViewerExcel ViewerFile SystemImage compareImage CropperImage GalleryImage LightboxLocation MapPDF ViewerPowerPoint ViewerQR CodeStep PlayerVideo Player
AI Kit
Agent Status CardChat MessageChat ThreadChat WidgetConversation ListFluid OrbGrid RevealMatrix OrbModel PickerPrompt InputReasoning IndicatorRule BuilderSuggestion ChipsTool Call TimelineUsage MeterVoice InputWorkflow Canvas
Text & Effects
Background PatternGravity LettersMarqueeTerminalText AnimateText Rotate
Mobile
Action SheetBottom Tab BarFABHaptic ButtonHero HeaderInstall PromptLarge Title HeaderNotification BannerOnboarding CarouselPicker WheelPull To RefreshSlide To ConfirmSticky CTA BarSwipe DeckSwipeable Tabs
Commerce
Cart drawerCategory pickerCheckout stepsCoupon inputFavorite buttonFilter panelListing cardListing gridOrder trackerPricePrice rangePricing tableProduct galleryQuantity stepperReviewsSeller card
Marketing Sections
App Download SectionBlog Cards SectionCTA SectionFAQ SectionFeature GridFeature ShowcaseHero SectionIntegrations SectionLogo CloudMarketing FooterMarketing HeaderMarketing SectionNewsletter SectionPricing SectionStats SectionSteps SectionTeam SectionTestimonials SectionTimeline SectionVideo Section
Blocks
Admin Dashboard PageAdmin ShellAI Chat PageAPI Keys PageAutomation Builder PageCheckout PageCRM Contact PageCRM Pipeline PageError PagesInbox PageInvoice PageKPI DashboardListing Detail PageLogin PageMarketplace Home PageMarketplace Search PageMarketplace ShellMobile App HomeOnboarding FlowOrder History PagePost Listing WizardPricing PageProfile PageRegister PageSettings PageUsers Admin Page
Templates
About PageAcademy PageAccessibility PageAffiliate PageAgency PageAI Product PageAppointment Booking PageBlog PageBlog Post PageBug Bounty PageCareers PageChangelog PageCommunity PageCompare PageContact PageCustomer Story PageCustomers PageDemo Booking PageDevelopers PageDocs Home PageDownload PageEnterprise PageEvents PageExperts PageFAQ PageFeature PageGlossary PageHelp Article PageHelp Center PageHome Services PageImpact PageIntegration Detail PageIntegrations PageJob Detail PageLanding PageLaunch PageLegal PageManifesto PagePortfolio PagePress PageProduct Tour PagePromo PageReal Estate PageReferral PageResearch Report PageRestaurant PageRoadmap PageROI Calculator PageSecurity PageSolutions PageStartups PageStatus PageStorefront PageSwitch PageTemplate Gallery PageTravel PageWaitlist PageYear in Review Page
Hooks & Utilities
AI ChatChart kitCommerceDate utilsFile exportFile typesFiltersForm validationHapticsInvoicingMotion presetsNavigationNumber formatRelative timeRomanian locationsSpreadsheetText matchTonesUIProvideruseClipboarduseConsentuseControllableStateuseCooldownuseDebounceuseKeyboardInsetuseLocaleuseLongPressuseMediaControlsuseMediaQueryuseOverflowItemsusePersistedStateuseScrollEdgesuseScrollStateuseSelectionuseShortcutuseStickToBottom
GalleryTheme

Hooks & Utilities

usePersistedState

Hooks & Utilities

usePersistedState React hook in TypeScript

useOverflowItemsuseScrollEdges
Live props
Options
key
storage
syncTabs
  1. Home
  2. Components
  3. Hooks & Utilities
  4. usePersistedState
Pro

usePersistedState React hook in TypeScript

v1.0.0·Added in 1.0.0

A React useState that survives reloads in localStorage, sessionStorage or a cookie, syncs across tabs and hydrates cleanly.

Switch the listing view in either card: the other card follows at once because both read the same key. Type a message: it is saved as you type. Press Reload to remount the demo and watch every value come back, or Delete draft to forget the draft. Open the page in a second tab and changes in local storage follow you there.

usePersistedState is a Pro React hook in the React hooks and utilities category, written in TypeScript for React 19. It installs as source with npx wingo-ui@latest add use-persisted-state, together with useControllableState.

Add to a project

Requirements: React 19, in Next.js (App Router or Pages), Vite or React Router. Installation guide · Next.js setup · Vite setup

npx wingo-ui@latest add use-persisted-state

usePersistedState is part of Pro, with 298 more Pro items: $8 a month or $150 once. 14-day refund before you download any Pro item. See plans

Usage

Import usePersistedState from @/hooks/use-persisted-state.

import { usePersistedState } from "@/hooks/use-persisted-state"

export function ListingsView() {
  const [view, setView] = usePersistedState<"list" | "grid">("listings:view", "list")

  return (
    <div role="group" aria-label="View" className="inline-flex gap-1">
      <button type="button" aria-pressed={view === "list"} onClick={() => setView("list")}>List</button>
      <button type="button" aria-pressed={view === "grid"} onClick={() => setView("grid")}>Grid</button>
    </div>
  )
}

API

  • key*default "ui-lab:preferences"
    string | null | undefined

    usePersistedState(key, defaultValue, options?): the storage key. null or an empty string turns persistence off (plain useState), so a component can take an optional persistKey prop.

  • defaultValue*
    T

    The value on the server, during hydration and whenever nothing is stored. The stored value replaces it right after hydration, so markup never mismatches.

  • storagedefault "local"
    "local" | "session" | "cookie"

    Where the value lives. cookie is the one a server can read: a Next layout reads cookies().get(persistedCookieName(key)) and passes the value as defaultValue, so a collapsed sidebar is collapsed on the first paint.

  • syncTabsdefault true
    boolean

    Follow changes made in other tabs (local storage only). Instances on the same page always stay in sync.

  • serialize / deserialize
    (value: T) => string / (raw: string) => T

    How the value becomes a string and back. Default JSON; a stored value that fails to parse falls back to defaultValue.

  • maxAgedefault 31536000
    number

    Cookie lifetime in seconds (one year).

  • returns
    [value: T, setValue: (next: SetStateAction<T>) => void, meta: { hydrated: boolean; remove(): void }]

    Like useState. meta.hydrated is false on the server and during hydration, so a component can skip the animation of the restore that follows. meta.remove forgets the stored value. Storage that throws (private mode, a full quota, blocked cookies) keeps working in memory for the session.

Parts

  • usePersistedControllableState

    hook

    The controlled / uncontrolled pattern of useControllableState with the uncontrolled value persisted: collapsed / defaultCollapsed / onCollapsedChange plus persistKey in one line. A controlled value is never written to storage. Signature: ({ key, value?, defaultValue, onChange?, ...options }) => [T, setValue, meta].

  • readPersisted

    function

    Reads the raw stored string outside React (event handlers, other stores). Signature: (key, storage?) => string | null.

  • writePersisted

    function

    Writes or removes (null) the raw string outside React; every hook reading the key updates. Signature: (key, raw | null, storage?, maxAge?) => void.

  • persistedCookieName

    function

    The cookie name a key is stored under, for server code: cookies().get(persistedCookieName(key)). Signature: (key) => string.

  • PersistedStorage

    type

    "local" | "session" | "cookie", where the value lives.

  • UsePersistedStateOptions

    type

    The options object: storage, serialize, deserialize, maxAge and syncTabs.

  • PersistedStateMeta

    type

    The third tuple item: { hydrated: boolean; remove(): void }.

  • UsePersistedControllableStateParams

    type

    The options of usePersistedControllableState: key, value, defaultValue, onChange plus the storage options.

Examples

Remembered settings

Two switches kept in local storage. Flip them, press Reload, and they come back as you left them.

Draft for this tab only

storage="session" keeps an unsent message until the tab closes.

Cookie the server can read

storage="cookie" so a layout can render the saved view on the first paint.

Dependencies

use-controllable-state

Files

  • hooks/use-persisted-state.ts

FAQ

Is the usePersistedState hook free?

The preview, props and docs are free; copying the source needs a Pro plan. See plans.

How do I install usePersistedState?

Run npx wingo-ui@latest add use-persisted-state. It also adds the Wingo UI item it builds on (useControllableState). With shadcn, add the @wingo-ui registry with your API key, then run npx shadcn@latest add @wingo-ui/use-persisted-state.

See also

useControllableStatehookuseDebouncehookuseConsenthookTheme ToggleuseMediaQueryhook

Used in

Onboarding FlowFile managerListing gridData TableDeal PipelineSidebarApp ShellEmoji PickerCommand MenuGlobal SearchTourBanner

and 8 more.

More React hooks and utilities

useScrollEdgeshookuseScrollStatehookuseSelectionhookuseShortcuthookuseStickToBottomhookAI Chatlib
All 36 React hooks and utilities
PrevioususeOverflowItemsNext useScrollEdges

Listings

  • Trek city bike

    $1,200

  • Sleeper sofa

    $850

  • MacBook Air M2

    $4,300

  • iPhone 13

    $1,850

Favorites

  • Trek city bike

    $1,200

  • Sleeper sofa

    $850

local: ui-lab:preferences:view, ui-lab:preferences:draft · syncTabs on