Skip to content

React useLocalStorage Hook

The useLocalStorage hook is a custom React hook that allows you to persist state in the browser’s local storage. It is similar to the useState hook, but it automatically saves the state to local storage and retrieves it when the component is re-rendered.

Here’s an example of how to use the useLocalStorage hook in a React component:

import React from 'react';
import { useLocalStorage } from './useLocalStorage';

function App() {
  const [count, setCount] = useLocalStorage('count', 0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
}

export default App;

In this example, we are using the useLocalStorage hook to create a state variable count that is persisted in local storage with the key 'count'. The initial value of count is 0, and we can increment or decrement it using the setCount function.

Implementation of useLocalStorage Hook

Here’s the implementation of the useLocalStorage hook:

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  // Retrieve the initial value from localStorage, or use the provided initial value
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error('Error reading from localStorage', error);
      return initialValue;
    }
  });

  // Function to update localStorage when the state changes
  const setValue = (value) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.error('Error setting localStorage', error);
    }
  };

  // Sync state with localStorage when key changes
  useEffect(() => {
    const storedValue = window.localStorage.getItem(key);
    if (storedValue !== null) {
      setStoredValue(JSON.parse(storedValue));
    }
  }, [key]);

  return [storedValue, setValue];
}

export default useLocalStorage;