useLocalStorage Hook
ReactJS
Hard
4 views
Problem Description
Create a useLocalStorage hook and use it for a text setting.
Output Format
Render a React component.
Constraints
Read in initializer and write on change with try/catch.
Official Solution
import React, { useEffect, useState } from 'react';
function useLocalStorage(key, initialValue) {
const [value, setValue] = useState(() => {
try {
const raw = localStorage.getItem(key);
if (raw == null) return initialValue;
return raw;
} catch {
return initialValue;
}
});
useEffect(() => {
try {
localStorage.setItem(key, String(value));
} catch {}
}, [key, value]);
return [value, setValue];
}
export default function App() {
const [name, setName] = useLocalStorage('meetcode_name', '');
return (
<div style={{ padding: 16, width: 520 }}>
<h2 style={{ marginTop: 0 }}>meetcode greeting</h2>
<input value={name} onChange={(e) => setName(e.target.value)} placeholder='Your name' style={{ width: '100%', padding: '10px 12px', borderRadius: 12, border: '1px solid #bbb' }} />
<div style={{ marginTop: 10, color: '#555' }}>{name ? 'Hello ' + name : 'Type your name'}</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!