← Back to all snippets
JAVASCRIPT

Custom useLocalStorage Hook for Persistent State

Create a reusable React custom hook, useLocalStorage, to automatically synchronize component state with the browser's localStorage, providing data persistence across sessions.

import React, { useState, useEffect } from 'react';

function getStorageValue(key, defaultValue) {
  // getting stored value
  if (typeof window !== 'undefined') {
    const saved = localStorage.getItem(key);
    const initial = saved !== null ? JSON.parse(saved) : defaultValue;
    return initial;
  }
  return defaultValue;
}

export const useLocalStorage = (key, defaultValue) => {
  const [value, setValue] = useState(() => {
    return getStorageValue(key, defaultValue);
  });

  useEffect(() => {
    // storing input value
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);

  return [value, setValue];
};

// Example Usage:
function SettingsComponent() {
  const [userName, setUserName] = useLocalStorage('userName', 'Guest');
  const [isDarkMode, setIsDarkMode] = useLocalStorage('isDarkMode', false);

  return (
    <div>
      <h2>User Settings</h2>
      <p>Hello, <input
        type="text"
        value={userName}
        onChange={(e) => setUserName(e.target.value)}
      /></p>
      <label>
        <input
          type="checkbox"
          checked={isDarkMode}
          onChange={(e) => setIsDarkMode(e.target.checked)}
        />
        Dark Mode
      </label>
      <p>Refresh the page to see the values persist!</p>
    </div>
  );
}

export default SettingsComponent;
How it works: The `useLocalStorage` custom hook provides a way to persist state in the browser's `localStorage`. It initializes state by attempting to retrieve a value from `localStorage` using the provided `key` or falling back to a `defaultValue`. The `useEffect` hook then ensures that whenever the `value` changes, it's automatically saved back to `localStorage`. This hook abstracts away the boilerplate of reading from and writing to `localStorage`, making it easy to create persistent UI settings or user preferences in any component.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs