AI Hints
Home›React Tutorial›Custom Hooks
React · Lesson 53 of 120

useLocalStorage

Remember values.

⏱ 2 min read▶ Video at 43:20🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

Here's a hook you'll use for real. It works just like use state, but the value survives a page reload, because it's saved in the browser's local storage.

  • Like useState
  • Survives reload
  • localStorage

Remembering a city

Use local storage works like use state, but remembers the value in the browser. The starting value is read from storage, if it's there. An effect saves the value whenever it changes. We type York, then reload the page. Run it. York is still there.

App.jsxjsx
import { useState, useEffect } from "react";
function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key);
    return saved !== null ? JSON.parse(saved) : initial;
  });
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];
}
export default function App() {
  const [city, setCity] = useLocalStorage("city", "");
  return (
    <div className="box">
      Deliver to: <input id="c" value={city} onChange={e => setCity(e.target.value)} placeholder="City" />
    </div>
  );
}
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}
Also uses actions.json
[{"type": "#c", "text": "York"}, {"reload": true}, {"wait": 300}]

Lazy starting value

Passing a function to use state means it only runs on the first render. That's useful when the starting value is slow to get, like reading storage. JSON stringify and parse let us store any value, not just text.

keyvalue
useState(() => ...)runs once
Storagetext only
JSON.stringifysave
JSON.parseload

Summary

Use local storage keeps values across reloads, behind a familiar interface. Next, use fetch.

Key takeaways
  • useLocalStorage
  • Survives reload
  • JSON
Next up: useFetch — a data hook