JavaScript includes built-in storage functionality that facilitates the development of web applications. This feature enables data storage directly in the user’s browser, offering two distinct types: Local Storage and Session Storage.
Whether you’re making a personal website, a business app, or anything else, understanding how to use sessionStorage can help you make web applications that are more responsive and user-friendly.
In this tutorial, I show how you can use sessionStorage in JavaScript and when not to use it, and also show you the difference between LOCAL and SESSION storage.
Table of Content
- Understanding JavaScript Session Storage
- Advantages of sessionStorage
- Disadvantages of sessionStorage
- Key Differences with Local Storage
- When to Use sessionStorage
- When Not to Use sessionStorage
- Conclusion
1. Understanding JavaScript Session Storage
1. What is sessionStorage?
sessionStorage
is like a short-term memory for JavaScript. It’s a tool for web developers to store data temporarily. Unlike localStorage
, which stores data for a long time, sessionStorage
is designed for short-term use, ideal for just one browser session.
- Scope and Isolation
Think of sessionStorage as a special container that exists within a particular window or tab. Each new tab or window creates its own distinct sessionStorage. This unique scope makes it an excellent choice when you need to isolate and manage data specific to a user’s interaction within that session.
- Lifetime and Transience
The info kept in sessionStorage is temporary. It only stays while the user has the tab or window open. Once they close it, the stored info goes away. This temporary feature is handy when you only need info for the current session and don’t want it to stick around longer.
2. Basic Usage
Let’s jump into the basics of using sessionStorage
. It operates through simple commands that allow you to store, retrieve, and manage data:
- Storing data:
sessionStorage.setItem('key', 'value');
- Retrieving data:
var value = sessionStorage.getItem('key');
- Removing data:
sessionStorage.removeItem('key');
- Clearing all data:
sessionStorage.clear();
3. Example
To put it into context, let’s consider a scenario where you want to store a user’s name during their session:
// Storing data sessionStorage.setItem('username', 'makitweb'); // Retrieving data var username = sessionStorage.getItem('username'); console.log(username); // Output: makitweb // Removing data sessionStorage.removeItem('username'); // Clearing all data sessionStorage.clear();
This straightforward example demonstrates how sessionStorage
can be utilized to store and manipulate data during a user’s session. Now, let’s explore the advantages and disadvantages of this client-side storage solution.
4. Example – Storing Object and Array
sessionStorage can only hold strings. If you want to put something other than a string then it is required to first convert it into a string using JSON.stringify()
.
const userInfoObject = { name: 'Yogesh singh', username: 'yogeshsingh', age: 30, }; sessionStorage.setItem('userinfo', JSON.stringify(userInfoObject));
Here, I stored userInfoObject
object in userinfo
key. You can similarly, store Array.
Read Stored Object and Array
const userData = JSON.parse(sessionStorage.getItem('userinfo')); console.log(userData.username); // Output: yogeshsingh
2. Advantages of sessionStorage
- Effortless Session-specific Data Management:
sessionStorage excels in handling data specific to a user’s session.
Perfect for storing preferences like themes, language settings, or custom configurations during a single visit to your web application.
- Lightweight Storage for a Responsive Experience:
Unlike its counterpart, localStorage, sessionStorage is designed for lighter data needs.
With a typical limit of around 5 MB per domain, it prevents overburdening the browser, ensuring a more responsive and efficient user experience.
3. Disadvantages of sessionStorage
- Temporary Data Lifespan:
- sessionStorage is designed for temporary data storage tied to a single browser session.
- While this ensures automatic data clearance upon tab or browser closure, it becomes a limitation when information persistence across sessions is required.
- Consider your application’s needs – if data longevity is crucial, alternatives like localStorage or server-side storage might be more appropriate.
- Storage Size Limitation:
- While sessionStorage is efficient for managing smaller data sets, its limited storage capacity (typically around 5 MB per domain) can pose challenges.
- For applications dealing with more extensive data storage requirements, exploring alternatives like localStorage or server-side storage is advisable.
4. Key Differences with Local Storage
- Temporary Data Lifespan:
- sessionStorage’s strength lies in its temporary nature, automatically clearing data when a user closes the tab or browser.
- This becomes a limitation when your application requires information to persist beyond a single session. Evaluate the necessity of data persistence for your specific use case.
- Storage Size Constraints:
- While sessionStorage is efficient for managing smaller data sets, its limited storage capacity (typically around 5 MB per domain) can pose challenges.
- For applications dealing with more extensive data storage requirements, exploring alternatives like localStorage or server-side storage is advisable.
5. When to Use sessionStorage
Now that we have a grasp of sessionStorage’s features, let’s delve into scenarios where it becomes an invaluable tool:
- User Preferences:
- Use Case: Store user-specific settings or preferences during their web application visit.
- Example: Remember a user’s chosen theme, language preference, or personalized settings.
- Form Data:
- Use Case: Preserve form input across multiple steps, enhancing the user experience during form navigation.
- Example: Navigate through different form sections or wizard steps without constant server requests.
- Temporary States:
- Use Case: Efficiently manage temporary states or variables without extensive server interaction.
- Example: Maintain specific states within a user session without relying on persistent storage solutions.
6. When Not to Use sessionStorage
While sessionStorage serves as a powerful tool for specific scenarios, it may not always be the most suitable choice. Here are situations where exploring alternative storage options is worth considering:
- Persistent Data:
- Situation: When your application requires data to persist beyond a single session.
- Consider: Explore alternatives like localStorage or server-side storage to ensure user-related information endures across visits.
- Large Datasets:
- Situation: sessionStorage excels for smaller data amounts but may not handle substantial datasets efficiently.
- Consider: Explore alternatives such as databases, server-side storage, or other client-side options like localStorage for more efficient handling of large datasets.
- Cross-Tab Communication:
- Situation: When your application relies on communication between different tabs or windows.
- Consider: If sessionStorage’s tab-specific scope presents limitations, investigate alternatives like localStorage or other inter-tab communication techniques.
7. Conclusion
In this guide, we’ve uncovered the basics of sessionStorage. Armed with this knowledge, you can make informed decisions about when to utilize this powerful tool. As you continue your journey into web development, remember that choosing the right storage option is a crucial aspect of building efficient and user-friendly applications. Happy coding!
If you found this tutorial helpful then don't forget to share.