JAVASCRIPT

Syncing React State with Local Storage using `useLocalStorage`

Build a `useLocalStorage` React hook to easily persist and retrieve component state in the browser's local storage, ensuring data remains available across page refreshes.

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.warn(`Error reading localStorage key "${key}":`, error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.warn(`Error setting localStorage key "${key}":`, error);
    }
  }, [key, value]);

  return [value, setValue];
}

// Example usage:
/*
function MyComponent() {
  const [name, setName] = useLocalStorage('user_name', 'Guest');

  return (
    <div>
      <p>Hello, {name}!</p>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
    </div>
  );
}
*/
How it works: The `useLocalStorage` hook provides a way to manage state that is synchronized with the browser's `localStorage`. It initializes its state by attempting to read from `localStorage` or falling back to an `initialValue`. An `useEffect` hook then updates `localStorage` whenever the `value` or `key` changes, ensuring data persistence even after the browser is closed and reopened. Error handling is included for robustness.

Need help integrating this into your project?

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

Hire DigitalCodeLabs