A custom hook for storing data in localStorage with automatic syncing between state and local storage.
jsx
import { useState } from 'react';
function useLocalStorage(key, initialValue) {
// Get value from localStorage or use the initial value
const storedValue = localStorage.getItem(key);
const [value, setValue] = useState(storedValue ? JSON.parse(storedValue) : initialValue);
// Update localStorage when value changes
const setStoredValue = (newValue) => {
setValue(newValue);
localStorage.setItem(key, JSON.stringify(newValue));
};
return [value, setStoredValue];
}
export default useLocalStorage;
jsx
import React, { useState } from 'react';
import useLocalStorage from './hooks/useLocalStorage';
function App() {
const [name, setName] = useLocalStorage('name', 'John Doe'); // Use localStorage hook with default 'John Doe'
const handleChange = (e) => {
setName(e.target.value); // Set new value
};
return (
<div>
<h1>Welcome, {name}!</h1>
<input type="text" value={name} onChange={handleChange} />
<p>Your name will be saved in localStorage</p>
</div>
);
}