CodingNic

Units & Preferences

Persist Unit Preference

Units & Preferences 10 min read

Persist Unit Preference

Task

Save the selected unit in localStorage and restore it on startup.

File / section

src/App.jsx

Change

Import useEffect. Initialize with useState(() => localStorage.getItem("weathernow-unit") || "metric"). Add useEffect(() => { localStorage.setItem("weathernow-unit", unit); }, [unit]);.

Why this change matters

The lazy initializer reads the stored value once, while the effect keeps storage synchronized after changes.

Test it

Switch to Fahrenheit, refresh the page, and confirm Fahrenheit remains selected.

Checkpoint

The unit preference survives a page refresh.

jsx
const [unit, setUnit] = useState(() =>
  localStorage.getItem("weathernow-unit") || "metric"
);

useEffect(() => {
  localStorage.setItem("weathernow-unit", unit);
}, [unit]);