CodeBlanks Logo Icon CodeBlanks

useLocalStorage

Learn to write a hook that syncs state to browser localStorage.

useLocalStorage

useLocalStorage stores a state in the browser's localStorage. The value survives page reload. It's a persistent version of useState.

The skeleton: const [value, setValue] = useState(() => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initial; });. The initial value is given as a function; so localStorage is only touched on first read.

To save changes, add a useEffect: useEffect(() => localStorage.setItem(key, JSON.stringify(value)), [value, key]);. So every change auto-saves.

JSON conversion

localStorage stores only strings. So to save objects or arrays, we convert to a string with JSON.stringify on write and back to an object with JSON.parse on read.

Error handling matters: a corrupted string can crash JSON.parse. So reads usually go inside a try/catch. Otherwise the app may crash on startup.

For type safety, one precaution: validate saved data against a shape. We keep it simple here, but in production this step is essential.

Practice useLocalStorage skeleton

Complete the skeleton. Write a useLocalStorage(key, initial) hook. Use useState with lazy init: () => { const saved = localStorage.getItem(key); return saved ? JSON.parse(saved) : initial; }. Add useEffect to call localStorage.setItem(key, JSON.stringify(value)); dependency [key, value]. Return [value, setValue]. Export the hook.

Starter code

App.jsx
import { useState, useEffect } from "react";

// Write the useLocalStorage hook here

Sample solution

App.jsx
import { useState, useEffect } from "react";

function useLocalStorage(key, initial) {
  const [value, setValue] = useState(() => {
    const saved = localStorage.getItem(key);
    return saved ? JSON.parse(saved) : initial;
  });
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];
}

export default useLocalStorage;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does lazy init do?

  • Reads every render
  • Touches localStorage only on first read Correct answer
  • Skips useEffect
  • Deletes state

Explanation: Lazy init only runs on first read.

2 Save method

Question
To save to the browser, call ____.
Answer
To save to the browser, call localStorage.setItem.

Explanation: Saved with localStorage.setItem.

3 Match the useLocalStorage steps

Term Meaning
useState Lazy init
localStorage.getItem Read
JSON.parse String to object
useEffect Save

All lessons in Intermediate