Sync Localstorage data Reactively in React Application

localStorage is a browser API that allows web applications to store key-value pairs locally on a user’s device. It provides a simple interface for storing data persistently, even after the browser is closed or the page is refreshed.

While localStorage provides persistence, integrating it with React in a reactive manner poses challenges. React’s component state management relies heavily on reactivity – any changes to the state should trigger re-renders and update the UI accordingly. Achieving this reactivity with localStorage requires syncing state changes with storage updates seamlessly.

To address this challenge, we can create a custom React hook that synchronizes component state with localStorage and updates automatically when the stored data changes. This custom hook leverages React’s useState and useEffect hooks to achieve reactivity.


const useLocalStorage = (key, initialValue) => {
  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(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
};

Using the useLocalStorage hook is straightforward. Simply provide a unique key for your data and an initial value, and the hook handles the rest.

const [count, setCount] = useLocalStorage('count', 0);<br>

Any changes to the count state will be automatically synced with localStorage, ensuring persistence across sessions while maintaining reactivity within the React application.

Tags

javascriptprogrammingreactwebweb-development