DEV Community

Cover image for Storing and Testing State in localStorage with React
Harpreet Kaur
Harpreet Kaur

Posted on

Storing and Testing State in localStorage with React

Managing state in a React application is a common challenge, and when it comes to persisting that state across sessions, localStorage is a handy solution. In this post, we'll explore a custom React hook, useSemiPersistentState, that simplifies the process of storing and testing state in localStorage.

The useSemiPersistentState Hook

import { useEffect, useState, Dispatch, SetStateAction } from "react";

const useSemiPersistentState = <T>(
  key: string,
  initialValue: T
): [T, Dispatch<SetStateAction<T>>] => {
  const [state, setState] = useState<T>(() => {
    try {
      const storedState = localStorage.getItem(key);
      return storedState ? JSON.parse(storedState) : initialValue;
    } catch (error) {
      // Handle parsing error, fallback to initial value
      console.error("Error parsing localStorage data:", error);
      return initialValue;
    }
  });

  useEffect(() => {
    // Save the value to localStorage whenever it changes
    localStorage.setItem(key, JSON.stringify(state));
  }, [key, state]);

  return [state, setState];
};

export { useSemiPersistentState };
Enter fullscreen mode Exit fullscreen mode

The useSemiPersistentState hook makes it easy to manage state in your React components while ensuring its persistence between page reloads.

Usage and Example

Let's consider a scenario where we want to persist the user's theme preference. Here's how you can use the hook:

import { useSemiPersistentState } from '<relative-path-to-your-hook-file>';

const ThemeSelector = () => {
  const [theme, setTheme] = useSemiPersistentState('theme', 'light');

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

  return (
    <div>
      <p>Current Theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
};

export default ThemeSelector;
Enter fullscreen mode Exit fullscreen mode

In this example, the ThemeSelector component effortlessly maintains the theme preference in localStorage, allowing the theme to persist across page reloads.

Testing Made Simple

Testing stateful components becomes easier with this hook. You can mock the localStorage object in your tests to simulate different scenarios and ensure that your components behave as expected.

Conclusion

The useSemiPersistentState hook provides an elegant solution for handling semi-persistent state in React applications. Whether you're building a theme switcher or saving user preferences, this hook simplifies the process and enhances the user experience.

Top comments (0)