JAVASCRIPT

Persist React State Across Sessions with useLocalStorage Hook

A custom React hook `useLocalStorage` simplifies synchronizing component state with local storage, ensuring data persists even after page refreshes.

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 reading from local storage:", error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error("Error writing to local storage:", error);
    }
  }, [key, value]);

  return [value, setValue];
}
How it works: This hook provides a convenient way to store and retrieve state from local storage, making it persistent across browser sessions. The `useState` initializer attempts to parse existing data from `localStorage` for the given `key`, falling back to `initialValue` if nothing is found or an error occurs. The `useEffect` hook then ensures that whenever the `value` or `key` changes, the updated `value` is serialized to JSON and saved to `localStorage`, keeping your state synchronized.

Need help integrating this into your project?

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

Hire DigitalCodeLabs