JAVASCRIPT

Persist React State with Custom useLocalStorage Hook

Discover how to create a `useLocalStorage` hook to effortlessly store and retrieve React state in the browser's local storage, ensuring data persistence across user sessions.

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

// Example Usage:
/*
import React from 'react';

function UserPreferences() {
  const [theme, setTheme] = useLocalStorage('appTheme', 'light');
  const [notificationsEnabled, setNotificationsEnabled] = useLocalStorage('notifications', true);

  return (
    <div>
      <button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
        Toggle Theme ({theme})
      </button>
      <p>Notifications: {notificationsEnabled ? 'Enabled' : 'Disabled'}</p>
      <button onClick={() => setNotificationsEnabled(!notificationsEnabled)}>
        Toggle Notifications
      </button>
    </div>
  );
}
*/
How it works: The `useLocalStorage` hook allows you to store and retrieve a state value from the browser's `localStorage`. It initializes the state by attempting to parse an existing item from `localStorage` or falling back to an `initialValue`. A `useEffect` hook then ensures that whenever the `storedValue` changes, it's automatically serialized to JSON and saved back into `localStorage`, providing persistent state management across page reloads.

Need help integrating this into your project?

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

Hire DigitalCodeLabs