Explain Codes LogoExplain Codes Logo

How to get JS variable to retain value after page refresh?

javascript
localstorage
sessionstorage
async-storage
Nikita BarsukovbyNikita BarsukovยทNov 15, 2024
โšกTLDR

Persist a JavaScript variable value across page reloads using localStorage or sessionStorage. Store and retrieve as follows:

// For when you absolutely have to save that secret super hero name localStorage.setItem('secretIdentity', 'value'); // Surprise! Turns out you're still the secret super hero! let value = localStorage.getItem('secretIdentity');

We have sessionStorage for temporary secret identities (because aren't we all a superhero just for a day? ๐Ÿ˜‰). It vanishes after the tab closes. For complex objects, turn them into JSON strings:

// Saving the world? Better jot that down! localStorage.setItem('worldSavingPlans', JSON.stringify({ secretPlan: 'Leave no pizza slice uneaten!' })); // Alright. What's the rule again? Oh, right! Pizza! let obj = JSON.parse(localStorage.getItem('worldSavingPlans'));

Remember, these fellows only handle strings. To save and retrieve objects, enlist the help of JSON.stringify() and JSON.parse().

Different Storing Options for Different Super Hero Jobs

Here's a guide to pick the right storing options depending on the superhero job at hand:

1. Persisting across browser restarts

localStorage is your hero when you want data to live past browser restarts. Think Batman - always there!

2. Retaining data within a single session

sessionStorage is your partner for a short session. Working while the tab is open, gone when it's closed - like a true ninja!

3. Facilitating cross-domain exchanges

The window.name property is a little-known hero facilitating cross-domain exchanges, be wary though, its secret identity isn't too secure.

4. Supporting older browsers

For those classic, stubborn older browsers that protest against modern storage options, rely on cookies. They may be tiny, but they're tough!

5. Abstracting storage functionality

To keep your identity a secret and your code DRY, consider a high-level library like localForage that abstracts storage in a consistent manner.

6. Storing sensitive data

A superhero always protects the innocent! Never store sensitive data on the client-side without encrypting it first.

7. Updating storage dynamically

Need to change your secret identity on the fly? Update the stored value with DOM events:

// Change your secret identity whenever you wish! No judgment here! yourSecretIdentity.addEventListener('change', (event) => { localStorage.setItem('secretIdentity', event.target.value); });

8. Handling complex data

For world domination plans complex objects, use JSON.stringify() to serialize before storage and JSON.parse() for retrieval.

Tips when using web storage

Now that you know how to use localStorage and sessionStorage, here are tips on effectively handling them:

Data Sync & Backups

For valuable data, consider synchronizing with a server to make a backup and share it across devices.

Browser Compatibility Techniques

Be a responsible coder and check browser support on caniuse.com. Make sure your app doesn't break on some browsers!

Guard Against XSS

Watch out for XSS attacks. Always sanitize and validate inputs before storing them.

Storage Size

Remember that localStorage or sessionStorage gives you up to 5MB per domain. That's a lot of pizzas errr... I mean, data!

Performance Effects

Storage operations cost you speed because they are I/O operations. So be kind to them, don't exhaust them!

Async Storage

Consider asynchronous storage APIs for non-blocking code. Your app's performance will thank you. ๐Ÿ˜‰