How to persist state with localStorage in React
Persisting component state across browser sessions enhances user experience by maintaining application state even after page refreshes or browser restarts. As the creator of CoreUI with extensive React experience since 2014, I’ve implemented state persistence in numerous production applications. The most effective approach combines useState with useEffect hooks to automatically save and restore state from localStorage. This pattern ensures data consistency while maintaining React’s declarative nature.
Use useEffect to save state to localStorage and initialize state from stored values.
import { useState, useEffect } from 'react'
function App() {
const [count, setCount] = useState(() => {
const saved = localStorage.getItem('count')
return saved ? parseInt(saved, 10) : 0
})
useEffect(() => {
localStorage.setItem('count', count.toString())
}, [count])
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
)
}
This code initializes the state from localStorage using a lazy initial state function, which only runs once during component mount. The useEffect hook automatically saves the current state value to localStorage whenever the state changes. The count persists across page refreshes and browser sessions, providing a seamless user experience.
Best Practice Note:
This is the same persistence pattern we use in CoreUI dashboard components for user preferences. Always handle JSON parsing errors with try-catch when storing complex objects to prevent application crashes.



