JAVASCRIPT

Synchronize State with Local Storage using useLocalStorage

Create a `useLocalStorage` custom hook to effortlessly persist and retrieve component state from the browser's local storage, ensuring data persists across sessions.

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

function useLocalStorage(key, initialValue) {
  // State to store our value
  // Pass initial state function to useState so logic is only executed once
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      // Parse stored json or if none return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      // If error also return initialValue
      console.log(error);
      return initialValue;
    }
  });

  // useEffect to update local storage when the state changes
  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.log(error);
    }
  }, [key, storedValue]); // Only re-run if key or storedValue changes

  return [storedValue, setStoredValue];
}

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

  const toggleTheme = () => {
    setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
  };

  const toggleNotifications = () => {
    setNotificationsEnabled((prev) => !prev);
  };

  return (
    <div style={{ padding: '20px', background: theme === 'dark' ? '#333' : '#f0f0f0', color: theme === 'dark' ? '#eee' : '#333' }}>
      <h1>User Settings</h1>
      <p>Current Theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
      <br />
      <p>Notifications: {notificationsEnabled ? 'Enabled' : 'Disabled'}</p>
      <button onClick={toggleNotifications}>Toggle Notifications</button>
      <p>Refresh the page to see how settings persist!</p>
    </div>
  );
}

export default UserSettings;
How it works: This snippet defines a `useLocalStorage` custom hook that allows React component state to be synchronized with the browser's local storage. It initializes the state by attempting to read from `localStorage` or falling back to an `initialValue`. A `useEffect` hook ensures that whenever the component's state (`storedValue`) or the `key` changes, the updated value is automatically saved to `localStorage`. This provides a seamless way to persist user preferences or other non-sensitive data across browser sessions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs