JAVASCRIPT

Synchronize State with `useLocalStorage` for Persistence

Create a custom `useLocalStorage` hook to persist your React component's state across page reloads by synchronizing it with the browser's local storage.

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 it works: The `useLocalStorage` hook allows you to persist a piece of state in the browser's local storage, so it remains available even after a page refresh. It initializes the state by trying to retrieve the value from local storage using `JSON.parse`. If no value is found or an error occurs, it falls back to the `initialValue`. A `useEffect` hook then runs whenever the `key` or `value` changes, automatically saving the current state to local storage using `JSON.stringify`. This ensures your component's state is always synchronized with local storage.

Need help integrating this into your project?

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

Hire DigitalCodeLabs