← Back to all snippets
JAVASCRIPT

Custom Hook for State Synchronization with Local Storage

Develop a custom useLocalStorage React hook to seamlessly synchronize component state with the browser's local storage, ensuring data persistence across sessions.

import { 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.error(error);
      return initialValue;
    }
  });

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

  return [storedValue, setStoredValue];
}

// Example Usage (in a component)
/*
function CounterWithStorage() {
  // Usage of our custom hook
  const [count, setCount] = useLocalStorage('my-counter-value', 0);
  const [name, setName] = useLocalStorage('user-name', 'Guest');

  return (
    <div style={{ padding: '20px', border: '1px solid #ccc', borderRadius: '8px', maxWidth: '400px', margin: '20px auto' }}>
      <h1>Counter: {count}</h1>
      <button onClick={() => setCount(prevCount => prevCount + 1)}>Increment</button>
      <button onClick={() => setCount(0)}>Reset Counter</button>

      <hr style={{ margin: '20px 0' }} />

      <h1>Hello, {name}!</h1>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Enter your name"
      />
      <p style={{ fontSize: '0.8em', color: '#666' }}>
        Try refreshing the page to see how values persist.
      </p>
    </div>
  );
}
// To use, render <CounterWithStorage /> in your App component.
*/
How it works: This snippet presents a `useLocalStorage` custom hook that allows React components to persist state in the browser's local storage. It initializes state by attempting to retrieve a value from local storage or using a provided `initialValue`. The `useEffect` hook then ensures that whenever the component's state changes, the updated value is automatically saved to local storage, providing data persistence across browser sessions and refreshes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs