localStorage is a browser feature that allows web applications to store data in the user's browser. React applications can use localStorage to save small pieces of data that should remain available after a page is refreshed or the browser is reopened.
JSON.stringify(), and when reading them back, use
JSON.parse().
localStorage is a browser storage mechanism used to store
key-value data.
localStorage
The stored data belongs to the website's browser storage area.
React applications can use localStorage when some small pieces of data need to remain available between page loads.
Examples include:
Data in localStorage is stored using a key and a value.
key → value
For example:
"username" → "Rahul"
The setItem() method stores a value in localStorage.
localStorage.setItem(
"username",
"Rahul"
);
Here, username is the key and Rahul is the value.
The getItem() method retrieves a value from localStorage.
const username =
localStorage.getItem("username");
console.log(username);
If the key exists, its stored value is returned.
The removeItem() method removes a specific key from localStorage.
localStorage.removeItem(
"username"
);
The clear() method removes all localStorage entries for the
current website's storage area.
localStorage.clear();
clear() carefully because it removes all localStorage data
for that website.
localStorage stores values as strings.
localStorage.setItem(
"age",
25
);
const age =
localStorage.getItem("age");
console.log(typeof age);
The retrieved value is a string, even if a number was originally provided.
Numbers can be stored, but they are retrieved as strings.
localStorage.setItem(
"age",
"25"
);
const age =
Number(
localStorage.getItem("age")
);
console.log(age);
Boolean values can be converted to strings before storing them.
localStorage.setItem(
"isLoggedIn",
"true"
);
const isLoggedIn =
localStorage.getItem(
"isLoggedIn"
) === "true";
console.log(isLoggedIn);
Objects cannot be stored directly in their original JavaScript object form.
Use JSON.stringify() to convert an object into a JSON string.
const student = {
name: "Rahul",
course: "React"
};
localStorage.setItem(
"student",
JSON.stringify(student)
);
Use JSON.parse() to convert the stored JSON string back into a
JavaScript value.
const student =
JSON.parse(
localStorage.getItem("student")
);
console.log(student.name);
Arrays can also be stored using JSON.
const courses = [
"HTML",
"CSS",
"React"
];
localStorage.setItem(
"courses",
JSON.stringify(courses)
);
const courses =
JSON.parse(
localStorage.getItem("courses")
);
console.log(courses);
After parsing, the value can be used as a normal JavaScript array.
React components can read and write localStorage using normal browser JavaScript APIs.
function App() {
localStorage.setItem(
"name",
"Rahul"
);
return <h2>React App</h2>;
}
However, storage operations should be designed carefully so they do not cause unnecessary work during rendering.
A stored value can be used as the initial state.
const [name, setName] = useState(
() => localStorage.getItem(
"name"
) || ""
);
The function form allows the initial value to be read when the state is initialized.
useEffect can synchronize React state with localStorage.
useEffect(() => {
localStorage.setItem(
"name",
name
);
}, [name]);
Whenever name changes, the stored value is updated.
import {
useEffect,
useState
} from "react";
function App() {
const [name, setName] = useState(
() => localStorage.getItem(
"name"
) || ""
);
useEffect(() => {
localStorage.setItem(
"name",
name
);
}, [name]);
return (
<div>
<input
value={name}
onChange={e =>
setName(e.target.value)
}
/>
<p>
Hello {name}
</p>
</div>
);
}
export default App;
A theme preference can be stored so that the selected theme remains after a page refresh.
localStorage.setItem(
"theme",
"dark"
);
The application can read the value when it starts.
const theme =
localStorage.getItem("theme");
A simple shopping cart can be stored as a JSON array.
const cart = [
{
id: 1,
name: "Laptop",
quantity: 1
},
{
id: 2,
name: "Mouse",
quantity: 2
}
];
localStorage.setItem(
"cart",
JSON.stringify(cart)
);
If a key does not exist, getItem() returns
null.
const name =
localStorage.getItem("name");
if (name === null) {
console.log(
"No name stored"
);
}
A default value can be used when no stored value exists.
const name =
localStorage.getItem(
"name"
) || "Guest";
If the key does not contain a usable value, "Guest" can be used.
A React button can remove a stored value.
function logout() {
localStorage.removeItem(
"user"
);
setUser(null);
}
This pattern can be useful when removing application preferences or session information stored in the browser.
When React state and localStorage need to stay synchronized,
useEffect is commonly used.
useEffect(() => {
localStorage.setItem(
"username",
username
);
}, [username]);
The dependency array makes the effect run when username changes.
Objects stored in localStorage should be serialized and parsed.
useEffect(() => {
localStorage.setItem(
"student",
JSON.stringify(student)
);
}, [student]);
To read it:
const savedStudent =
JSON.parse(
localStorage.getItem("student")
);
JSON.stringify().JSON.parse() when reading stored JSON.clear() when only one item should be removed.React State
↓
JSON.stringify()
↓
localStorage
↓
getItem()
↓
JSON.parse()
↓
React State
This is a common pattern for persisting objects and arrays.
| React State | localStorage |
|---|---|
| Manages UI state | Stores data in the browser |
| Updates cause React re-rendering | Changing storage does not automatically re-render React |
| Lives with the component/application state | Can persist across page reloads |
| Useful for active UI data | Useful for simple client-side persistence |
import {
useEffect,
useState
} from "react";
function Profile() {
const [user, setUser] = useState(
() => {
const savedUser =
localStorage.getItem(
"user"
);
return savedUser
? JSON.parse(savedUser)
: {
name: "",
course: ""
};
}
);
useEffect(() => {
localStorage.setItem(
"user",
JSON.stringify(user)
);
}, [user]);
return (
<div>
<input
value={user.name}
placeholder="Name"
onChange={e =>
setUser({
...user,
name:
e.target.value
})
}
/>
<input
value={user.course}
placeholder="Course"
onChange={e =>
setUser({
...user,
course:
e.target.value
})
}
/>
<h3>
{user.name}
</h3>
<p>
{user.course}
</p>
</div>
);
}
export default Profile;
JSON.stringify() for objects and arrays.JSON.parse() when reading stored JSON data.removeItem() when deleting one stored value.clear() only when all site storage should be removed.State
↓
JSON.stringify()
↓
localStorage
↓
getItem()
↓
JSON.parse()
↓
State
localStorage stores key-value data in the browser.setItem() stores a value.getItem() retrieves a value.removeItem() removes a specific value.clear() removes all localStorage entries for the site's storage area.JSON.stringify() to store objects and arrays.JSON.parse() to read stored JSON data.useState and useEffect can be used to synchronize React state with localStorage.Question: Which method is used to store a value in localStorage?