useLocalStorage
Here's an example of a custom hook that uses the useState
Hook to persist state in localStorage
:
import { useState } from 'react'
function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key)
return item ? JSON.parse(item) : initialValue
} catch (error) {
console.log(error)
return initialValue
}
})
function setValue(value) {
try {
const valueToStore =
value instanceof Function ? value(storedValue) : value
setStoredValue(valueToStore)
window.localStorage.setItem(key, JSON.stringify(valueToStore))
} catch (error) {
console.log(error)
}
}
return [storedValue, setValue]
}
This custom hook takes a key
and an initialValue
as parameters and returns an array with two values: a storedValue
and a setValue
function. We use the useState
Hook to initialize the storedValue
state with the value from localStorage
. When the setValue
function is called, we update the storedValue
state and also update the value in localStorage
.
To use this custom hook, you would simply call it in your functional component and pass in the key
and initialValue
parameters:
function MyComponent() {
const [name, setName] = useLocalStorage('name', '')
function handleChange(event) {
setName(event.target.value)
}
return (
<div>
<label htmlFor="name">Name:</label>
<input type="text" id="name" value={name} onChange={handleChange} />
</div>
)
}
In this example, we call the useLocalStorage
hook with a key
of name
and an initialValue
of an empty string. We use the setValue
function to update the name
state when the input is changed. By using the useLocalStorage
Hook, we can easily persist state in localStorage
and retrieve it even after the page is refreshed or closed.