Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

saveToLocalStorage

Saves a value to localStorage after serializing it to JSON.

TypeScript
Copied!
1/**
2 * Saves a value to localStorage after serializing it to JSON.
3 *
4 * @param key - The key under which the value will be stored.
5 * @param value - The value to store (will be JSON-stringified).
6 */
7export function saveToLocalStorage<T>(key: string, value: T): void {
8  try {
9    const serialized = JSON.stringify(value);
10    localStorage.setItem(key, serialized);
11  } catch (e) {
12    console.error('Failed to save to localStorage:', e);
13  }
14}
  • Type-Safe Interface

    Supports generics to preserve TypeScript type information during development, enhancing developer experience.

  • Automatic Serialization

    Converts complex data structures into JSON automatically, reducing boilerplate and potential bugs.

  • Graceful Error Handling

    Catches and logs errors to prevent app crashes due to serialization issues or storage limits.

  • Encapsulation of Storage Logic

    Provides a reusable abstraction over localStorage.setItem, promoting cleaner and more maintainable code.

Tests | Examples

TypeScript
Copied!
1beforeEach(() => {
2  localStorage.clear();
3  jest.clearAllMocks();
4});
5
6test('saveToLocalStorage - stores stringified value', () => {
7  saveToLocalStorage('user', { name: 'Alice' });
8  expect(localStorage.getItem('user')).toBe(JSON.stringify({ name: 'Alice' }));
9});
10
11test('saveToLocalStorage - handles primitive values', () => {
12  saveToLocalStorage('count', 5);
13  expect(localStorage.getItem('count')).toBe('5');
14});
15
16test('saveToLocalStorage - catches errors gracefully', () => {
17  const circular: any = {};
18  circular.self = circular;
19  const spy = jest.spyOn(console, 'error').mockImplementation(() => {});
20  saveToLocalStorage('bad', circular);
21  expect(console.error).toHaveBeenCalled();
22});

Common Use Cases

  • Persisting UI Preferences

    Save user settings like theme, layout, or language selection between sessions.

  • Caching API Responses

    Store frequently requested data locally to reduce network calls.

  • Draft Management

    Save in-progress form input or content drafts to avoid accidental loss.

  • Feature Flags and Experiment Data

    Store flag values or variant assignments for A/B testing scenarios.

Codebase: Utilities -> Storage -> saveToLocalStorage | Yevhen Klymentiev