Custom Hook for Using Local Storage State
In React, managing state with local storage allows you to persist data between page reloads. Here's how you can create a custom hook called useLocalStorageState
to easily integrate local storage into your React components.
useLocalStorageState
Hook
Basic This custom hook syncs a piece of state with local storage so that the state persists even if the user refreshes the page or closes the browser.
import { useState, useEffect } from 'react'
export let useLocalStorageState = (key, defaultValue = '', options = {}) => {
let { serialize = JSON.stringify, deserialize = JSON.parse } = options
let [state, setState] = useState(() => {
let valueInLocalStorage = window.localStorage.getItem(key)
if (valueInLocalStorage) {
return deserialize(valueInLocalStorage)
}
return defaultValue
})
useEffect(() => {
window.localStorage.setItem(key, serialize(state))
}, [key, state, serialize])
return [state, setState]
}
How It Works
- useState: Initializes the state by checking if the value already exists in local storage. If it does, the hook returns the deserialized value. Otherwise, it returns the default value.
- useEffect: Each time the state changes, the new value is serialized and stored in local storage under the specified
key
.
Customization
The hook supports custom serialization and deserialization functions through the options
parameter. By default, it uses JSON.stringify
and JSON.parse
, but you can modify this for custom formats.
Usage Example
import { useLocalStorageState } from './useLocalStorageState'
function Counter() {
const [count, setCount] = useLocalStorageState('count', 0)
const increment = () => setCount((c) => c + 1)
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
)
}
Why Use Local Storage?
Local storage is a simple way to store data in the browser, and it persists across page reloads. Using useLocalStorageState
, you can:
- Save user preferences (e.g., theme settings).
- Persist form data between sessions.
- Store app state like counters, shopping carts, or settings.
Caveats
- Size Limitations: Local storage has a limit of around 5MB per domain. Be mindful of this when storing large amounts of data.
- Security: Local storage data is stored in plain text, so avoid storing sensitive information like passwords or tokens.
- Syncing Across Tabs: Changes in local storage made in other browser tabs or windows won’t automatically sync with your React state. You can handle this by adding an event listener to the
storage
event if needed.
Conclusion
The useLocalStorageState
hook provides a reusable and efficient way to manage persistent state in your React applications. It's perfect for situations where you want to remember user settings or preferences across page reloads, making your app more user-friendly.
Happy coding!