localStorage is a small storage space inside your web browser. A website can use it to save information on your device, and the information stays there even after you close the browser or restart your computer.
How it works
Think of it as a tiny notebook that each website gets to write in. Every entry has a name (called a key) and a value. A website can only read its own notebook, not the notebooks of other websites.
Basic example
// Save something
localStorage.setItem('theme', 'dark');
// Read it back
const theme = localStorage.getItem('theme');
// Delete it
localStorage.removeItem('theme');
// Delete everything
localStorage.clear();
localStorage can only store text. To save an object or list, convert it first:
const user = { name: 'Ragul', age: 22 };
localStorage.setItem('user', JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem('user'));
What is it used for?
- Remembering dark mode or light mode
- Saving a draft of a form
- Keeping a to-do list
- Remembering a user's language choice
Good things about it
- Easy to use
- Data stays after closing the browser
- Holds about 5 MB
- Works in all modern browsers
Things to be careful about
- Not secure. Never store passwords or private tokens in it.
-
Text only. Objects need
JSON.stringifyandJSON.parse. - Small size. It is not meant for large data.
- Can be cleared. Users can delete it anytime from browser settings.
Top comments (0)