JAVASCRIPT

Persisting State with a useLocalStorage React Hook

Develop a `useLocalStorage` custom hook for React to easily store and retrieve component state in the browser's local storage, ensuring data persistence across sessions.

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:
/*
import React from 'react';
import useLocalStorage from './useLocalStorage'; // Assuming useLocalStorage.js

function ThemeSwitcher() {
  const [theme, setTheme] = useLocalStorage('app-theme', 'light');

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

  return (
    <div style={{ background: theme === 'light' ? '#fff' : '#333', color: theme === 'light' ? '#333' : '#fff' }}>
      <h1>Current theme: {theme}</h1>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}
*/
How it works: The `useLocalStorage` hook allows a React component's state to be synchronized with the browser's local storage. On initialization, it attempts to load the value from local storage. Any subsequent changes to the state automatically persist the new value, making data available even after the user closes and reopens the browser.

Need help integrating this into your project?

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

Hire DigitalCodeLabs