sessionStorage is a browser storage mechanism that allows web applications to store data for the current browser session. React applications can use sessionStorage to temporarily preserve small pieces of data while the user is working with a website.
JSON.stringify() when saving and JSON.parse() when
reading the data.
sessionStorage is a browser storage API used to store
key-value data for the current page session.
sessionStorage
It is similar to localStorage, but its lifetime is generally limited to the current browser tab session.
sessionStorage can be useful when information should remain available while the user is working in a browser tab but does not need to be stored as a long-term browser preference.
Examples include:
sessionStorage stores data using a key and a value.
key → value
For example:
"username" → "Rahul"
The setItem() method stores a value in sessionStorage.
sessionStorage.setItem(
"username",
"Rahul"
);
Here, username is the key and Rahul is the value.
The getItem() method retrieves a stored value.
const username =
sessionStorage.getItem(
"username"
);
console.log(username);
The removeItem() method removes a specific item from
sessionStorage.
sessionStorage.removeItem(
"username"
);
The clear() method removes all sessionStorage entries for the
current website's storage area.
sessionStorage.clear();
clear() carefully because it removes all sessionStorage
data for that website.
sessionStorage stores values as strings.
sessionStorage.setItem(
"age",
25
);
const age =
sessionStorage.getItem("age");
console.log(typeof age);
The retrieved value is a string.
Numbers can be stored as strings and converted back to numbers when needed.
sessionStorage.setItem(
"age",
"25"
);
const age =
Number(
sessionStorage.getItem("age")
);
console.log(age);
Boolean values can be represented as strings.
sessionStorage.setItem(
"isLoggedIn",
"true"
);
const isLoggedIn =
sessionStorage.getItem(
"isLoggedIn"
) === "true";
console.log(isLoggedIn);
JavaScript objects should be converted into JSON strings before storing them.
const student = {
name: "Rahul",
course: "React"
};
sessionStorage.setItem(
"student",
JSON.stringify(student)
);
Use JSON.parse() to convert the stored JSON string back into a
JavaScript object.
const student =
JSON.parse(
sessionStorage.getItem(
"student"
)
);
console.log(student.name);
Arrays can also be stored using JSON.
const courses = [
"HTML",
"CSS",
"React"
];
sessionStorage.setItem(
"courses",
JSON.stringify(courses)
);
const courses =
JSON.parse(
sessionStorage.getItem(
"courses"
)
);
console.log(courses);
After parsing, the value can be used as a normal JavaScript array.
React components can access sessionStorage using the browser's
sessionStorage API.
function App() {
sessionStorage.setItem(
"name",
"Rahul"
);
return (
<h2>
React App
</h2>
);
}
Storage operations should be used carefully so that unnecessary work is not performed during rendering.
A stored value can be used as the initial state of a React component.
const [name, setName] = useState(
() =>
sessionStorage.getItem(
"name"
) || ""
);
The useEffect Hook can synchronize React state with
sessionStorage.
useEffect(() => {
sessionStorage.setItem(
"name",
name
);
}, [name]);
The effect runs when name changes.
import {
useEffect,
useState
} from "react";
function App() {
const [name, setName] = useState(
() =>
sessionStorage.getItem(
"name"
) || ""
);
useEffect(() => {
sessionStorage.setItem(
"name",
name
);
}, [name]);
return (
<div>
<input
value={name}
onChange={e =>
setName(
e.target.value
)
}
/>
<p>
Hello {name}
</p>
</div>
);
}
export default App;
sessionStorage can temporarily preserve form information while a user works through a page.
sessionStorage.setItem(
"email",
"student@example.com"
);
The value can be read later during the same browser tab session.
A multi-step form can store temporary information between steps.
const formData = {
name: "Rahul",
email: "rahul@example.com",
course: "React"
};
sessionStorage.setItem(
"formData",
JSON.stringify(formData)
);
The next step can retrieve the saved data.
If a key does not exist, getItem() returns null.
const name =
sessionStorage.getItem(
"name"
);
if (name === null) {
console.log(
"No name stored"
);
}
You can provide a default value when no stored data is available.
const name =
sessionStorage.getItem(
"name"
) || "Guest";
If no usable value is stored, "Guest" can be used.
A React button can remove a specific sessionStorage item.
function removeName() {
sessionStorage.removeItem(
"name"
);
setName("");
}
When React state and sessionStorage need to stay synchronized,
useEffect is commonly used.
useEffect(() => {
sessionStorage.setItem(
"username",
username
);
}, [username]);
The effect runs whenever username changes.
Objects and arrays can be synchronized with sessionStorage using JSON.
useEffect(() => {
sessionStorage.setItem(
"student",
JSON.stringify(student)
);
}, [student]);
To read the value:
const savedStudent =
JSON.parse(
sessionStorage.getItem(
"student"
)
);
JSON.stringify().JSON.parse() when reading JSON data.clear() when only one item should be removed.React State
↓
JSON.stringify()
↓
sessionStorage
↓
getItem()
↓
JSON.parse()
↓
React State
This is a common pattern for storing objects and arrays temporarily.
| localStorage | sessionStorage |
|---|---|
| Designed for persistent browser storage | Designed for storage associated with the current page session |
| Data can remain after a browser is closed and reopened | Data is generally cleared when the page session ends |
| Useful for longer-lived preferences | Useful for temporary session data |
| Uses setItem() and getItem() | Uses setItem() and getItem() |
Both storage mechanisms store data as strings.
import {
useEffect,
useState
} from "react";
function Profile() {
const [user, setUser] = useState(
() => {
const savedUser =
sessionStorage.getItem(
"user"
);
return savedUser
? JSON.parse(savedUser)
: {
name: "",
course: ""
};
}
);
useEffect(() => {
sessionStorage.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 session storage should be removed.State
↓
JSON.stringify()
↓
sessionStorage
↓
getItem()
↓
JSON.parse()
↓
State
sessionStorage stores key-value data for the current page session.setItem() stores a value.getItem() retrieves a value.removeItem() removes a specific value.clear() removes all sessionStorage 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 synchronize React state with sessionStorage.Question: Which method is used to store a value in sessionStorage?