Jacob Paris
← Back to all content

Persist data client-side in React with useLocalStorageState

Antonio Stoilkov built an excellent React hook for persisting state in local storage.

It's called useLocalStorageState and it works just like useState, but page navigations and refreshes won't reset it.

Let's look at a simple example of a form that needs a title and description.

  • These are both uncontrolled inputs, so we're using defaultValue to set the initial value.
  • We're also using onChange to track any updates in our state.

If the user refreshes the page before they submit the form, they won't lose any of their work.

jsx
import { useLocalStorageState } from "use-local-storage-state"
export default function Page() {
const [title, setTitle] = useLocalStorageState("title", {
defaultValue: "",
})
const [description, setDescription] =
useLocalStorageState("description", {
defaultValue: "",
})
return (
<form
method="POST"
onSubmit={(event) => {
setTitle()
setDescription()
}}
>
<label>
Title
<input
type="text"
defaultValue={title}
onChange={(e) => setTitle(e.target.value)}
/>
</label>
<label>
Description
<input
type="text"
defaultValue={description}
onChange={(e) => setDescription(e.target.value)}
/>
</label>
<button type="submit">Submit</button>
</form>
)
}
Professional headshot
Moulton
Moulton

Hey there! I'm a developer, designer, and digital nomad building cool things with Remix, and I'm also writing Moulton, the Remix Community Newsletter

About once per month, I send an email with:

  • New guides and tutorials
  • Upcoming talks, meetups, and events
  • Cool new libraries and packages
  • What's new in the latest versions of Remix

Stay up to date with everything in the Remix community by entering your email below.

Unsubscribe at any time.