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

