A dependency array is the second argument to useEffect. React compares its values with the previous render: changed values rerun the effect; unchanged values skip it. section 4.1.4
Use the array to match an effect’s intended lifecycle:
- Omit the array to run the effect after every render. section 4.4
- Pass [] to run the effect once when the component mounts, such as when registering a window resize listener or fetching initial data. section 4.1.2 section 4.2.3
- List every value used by the effect, such as [user] for saving a selected user to local storage or [dispatch] for loading bookables. section 4.1.4 section 6.3.3
- Return a cleanup function when the effect creates a listener, subscription, timer, or request-related resource; React runs cleanup before rerunning the effect and when the component unmounts. section 4.1.3
Persisting a selected user
One effect reads a stored user on mount with []; another saves the current user whenever user changes with [user]. Selecting a different option updates state and triggers only the saving effect. 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.
Shows dependency arrays in a complete user-storage component, including mount-time loading and change-driven persistence. section 4.1.4


