Persist Toggle Setting
ReactJS
Hard
6 views
Problem Description
Save a boolean setting in localStorage and restore it on load.
Output Format
Render a React component.
Constraints
Read localStorage in initializer and write on changes.
Official Solution
import React, { useEffect, useState } from 'react';
export default function App() {
const [compact, setCompact] = useState(() => {
try {
return localStorage.getItem('meetcode_compact') === '1';
} catch {
return false;
}
});
useEffect(() => {
try {
localStorage.setItem('meetcode_compact', compact ? '1' : '0');
} catch {}
}, [compact]);
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode settings</h2>
<label style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<input type='checkbox' checked={compact} onChange={(e) => setCompact(e.target.checked)} />
Compact mode
</label>
<div style={{ marginTop: 12, border: '1px solid #eee', borderRadius: 16, padding: compact ? 10 : 18 }}>
<strong>Preview card</strong>
<div style={{ color: '#555', marginTop: 8 }}>Padding changes based on setting.</div>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!