JAVASCRIPT

Persist React State with `useLocalStorage` Custom Hook

A reusable React hook to store and retrieve state from browser's localStorage, maintaining data across page refreshes for user preferences or forms.

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);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      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]);

  return [storedValue, setStoredValue];
}

// How to use it:
// function ThemeToggler() {
//   const [theme, setTheme] = useLocalStorage('appTheme', 'light');

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

//   return (
//     <button onClick={toggleTheme}>
//       Switch to {theme === 'light' ? 'dark' : 'light'} Theme
//     </button>
//   );
// }
How it works: This custom hook synchronizes a React state variable with an entry in the browser's `localStorage`. It initializes the state by attempting to retrieve a value from `localStorage` or falling back to a provided initial value. An `useEffect` hook ensures that whenever the state changes, the new value is automatically saved to `localStorage`, making the state persistent across sessions and page refreshes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs