JAVASCRIPT

Synchronize React State with Local Storage using useLocalStorage

Create a React useLocalStorage hook to effortlessly persist and retrieve component state across browser sessions, simplifying data management for user preferences or forms.

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

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error(error);
    }
  }, [key, value]);

  return [value, setValue];
}

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

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

//   return (
//     <div>
//       <p>Current Theme: {theme}</p>
//       <button onClick={toggleTheme}>Toggle Theme</button>
//     </div>
//   );
// }
How it works: The `useLocalStorage` hook initializes state by attempting to read from `localStorage` using the provided `key`. If no item is found or an error occurs, it falls back to `initialValue`. An `useEffect` then ensures that whenever the `value` state changes, it's automatically serialized to JSON and stored in `localStorage` under the given `key`, providing persistent state management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs