liveBook · Manning

Local storage

As explained in React Hooks in Action: With Suspense and Concurrent Mode

Local storage is a browser-provided key-value storage mechanism that persists string data across page visits.

Local storage is browser-provided key-value storage for string data that persists across page visits. In a React component, effects can read a saved value when the component first mounts and write changes when state changes. section 4.1.4

Remembering a selected user

A user picker initializes its state with a default user, reads any saved user from local storage through an effect with an empty dependency array, and saves the current user through an effect depending on user. After a refresh, the previously selected user is restored. section 4.1.4

Listing 4.4 Using local storage
import React, { useState, useEffect } from "react";
 
export default function UserStorage () {
  const [user, setUser] = useState("Sanjiv");
 
  useEffect(() => {
    const storedUser = window.localStorage.getItem("user");   #1
 
    if (storedUser) {
      setUser(storedUser);
    }
  }, []);                                                     #2
 
  useEffect(() => {                                           #3
    window.localStorage.setItem("user", user);                #4
  }, [user]);                                                 #5
 
  return (
    <select value={user} onChange={e => setUser(e.target.value)}>
      <option>Jason</option>
      <option>Akiko</option>
      <option>Clarisse</option>
      <option>Sanjiv</option>
    </select>
  );
}
#1 Read the user from local storage.
#2 Run this effect only when the component first mounts.
#3 Specify a second effect.
#4 Save the user to local storage.
#5 Run this effect whenever the user changes.

Inspect the focused React listing showing getItem, setItem, mount-only initialization, and state-dependent persistence. section 4.1.4

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Demonstrates reading and writing values through effects, including mount-only and state-dependent dependency behavior.
Examples
Uses a user-selection dropdown whose saved choice is restored after refreshing the page.
What it assumes
Assumes familiarity with React function components, useState, useEffect, and dependency arrays.
What you can do after
Builds a React user picker that restores and persists its selected value with local storage.
How it connects
Connects local storage with React state, effects, dependency arrays, component rendering, and page reloads.

Also explained in

Compare how 2 books explain local storage →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.