Harnessing the Power of Local Storage with a Custom React Hook

If you're a React developer, you know that managing state can be a crucial aspect of creating a dynamic and responsive user interface. One common challenge is persisting state across page reloads or even when the user navigates away from your application. This is where local storage comes into play, and in this blog post, we'll explore a custom React hook designed to simplify the process: useLocalStorage.

Understanding useLocalStorage

/* useLocalStorage */

import { useState } from "react";

const useLocalStorage = (key, initialValue) => {
  const [value, setValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      alert("Something went wrong.");
      console.log(error);    
    }
  });

  const setLocalValue = (value) => {
    try {
      window.localStorage.setItem(key, JSON.stringify(value));
      setValue(value)
    } catch (error) {
      alert("Something went wrong.");
      console.log(error);   
    }
  }

  return [value, setLocalValue];
}

export default useLocalStorage;

How It Works

The useLocalStorage hook leverages the useState hook from React to manage state. It takes two parameters - key and initialValue. The key is a unique identifier for the stored value, and initialValue is the default value if no stored value is found.

The initial state is set by attempting to retrieve a value from local storage using the provided key. If a value is found, it's parsed from JSON; otherwise, the initialValue is used. This ensures that the component using this hook starts with the correct state.

The hook returns an array containing the current state (value) and a function (setLocalValue) to update the state and persist it to local storage.

Practical Use Case

Let's consider a scenario where you want to store user preferences, such as theme selection or language choice. You can use useLocalStorage to seamlessly manage these preferences, providing a smooth user experience even after a page refresh.

import React from 'react';
import useLocalStorage from './useLocalStorage';

const App = () => {
  const [theme, setTheme] = useLocalStorage('theme', 'light');

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

  return (
    <div className={`app ${theme}`}>
      <h1>Local Storage Magic with React</h1>
      <p>Current Theme: {theme}</p>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </div>
  );
}

export default App;

In this example, the application maintains the theme state in local storage. The toggleTheme function switches between 'light' and 'dark' themes, and the selected theme persists across page reloads.

Conclusion

The useLocalStorage hook is a handy tool for React developers looking to seamlessly integrate local storage into their applications. By abstracting the complexities of local storage management, this custom hook enhances code readability and promotes reusability. Whether you're building a simple app or a complex web application, consider incorporating this hook to elevate your state management game. Happy coding!