In React, state usually disappears when you refresh the page. Imagine building a form, a theme toggle, or a shopping cart — once the user reloads, everything resets. That’s not always a good experience.
Luckily, the browser gives us localStorage, which can save data in the user’s browser even after closing or reloading the tab. By combining localStorage with React hooks, we can create a custom hook that persists state automatically.
In this post, we’ll build a reusable useLocalState
hook.
React’s built-in useState is great for temporary state:
jsxconst [count, setCount] = useState(0)
But after a refresh, count
resets back to 0. If we want state that survives reloads, we need localStorage.
jsximport { useState, useEffect } from "react"
function useLocalState(key, defaultValue) {
const [state, setState] = useState(() => {
try {
const stored = localStorage.getItem(key)
return stored ? JSON.parse(stored) : defaultValue
} catch {
return defaultValue
}
})
useEffect(() => {
localStorage.setItem(key, JSON.stringify(state))
}, [key, state])
return [state, setState]
}
export default useLocalState
jsximport React from "react"
import useLocalState from "./useLocalState"
function Counter() {
const [count, setCount] = useLocalState("count", 0)
return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(c => c + 1)}>Increase</button>
<button onClick={() => setCount(c => c - 1)}>Decrease</button>
</div>
)
}
export default Counter
Now, if you refresh the page, the counter value stays the same 🎉
Copythight © All Rights Reserved.