Local Storage and Persistence

Sometimes you want data to stick around even after the user closes the page. Browser localStorage provides a simple way to save data locally — no server required. It's perfect for user preferences, draft content, or simple app state.

How localStorage Works

localStorage is a key-value store built into every browser. You save data with a key (a name) and retrieve it later using that same key. Data persists until explicitly deleted — it survives page reloads, browser restarts, even computer reboots.

// Save data
localStorage.setItem('username', 'alex');

// Retrieve data
const name = localStorage.getItem('username');

// Remove data
localStorage.removeItem('username');

Each website gets its own isolated storage — your site can't read another site's localStorage, and vice versa.

Storing Complex Data

localStorage only stores strings. To save objects or arrays, convert them to JSON first, then parse them when reading back.

// Save an array
const todos = [{text: 'Learn JS', done: false}];
localStorage.setItem('todos', JSON.stringify(todos));

// Load the array
const saved = localStorage.getItem('todos');
const loaded = saved ? JSON.parse(saved) : [];

Always handle the case where localStorage is empty — getItem() returns null if the key doesn't exist.

Practical Patterns

A common pattern loads data on page startup and saves after every change:

// Load on startup
let data = JSON.parse(localStorage.getItem('myData')) || defaultValue;

// Save after changes
function saveData() {
  localStorage.setItem('myData', JSON.stringify(data));
}

Call saveData() whenever your data changes, and it automatically persists.

Limitations to Know

localStorage has important constraints. It only stores strings (hence the JSON conversion). Most browsers limit storage to about 5MB per site. Data is not encrypted — don't store sensitive information. And it's synchronous, meaning large operations can briefly freeze your page.

For simple use cases like remembering user preferences or saving form drafts, these limitations rarely matter. For anything more complex, you'll want a proper database.

When to Use localStorage

localStorage shines for user preferences (dark mode, language), draft content (unsaved form data), simple app state (todo lists, bookmarks), and caching API responses. It's not suitable for sensitive data, large datasets, or data that needs to sync across devices.

See More

Further Reading

You need to be signed in to leave a comment and join the discussion