How to Use Local Storage in React with a Custom Hook

Discover how to use local storage in React and create a custom hook for enhanced functionality.

Published on

2 min read

When building web applications, managing data efficiently is key. Local storage offers a simple way to store data in the user's browser, allowing us to persist state across page reloads. Let's dive into how we can use local storage in JavaScript and then see how we can integrate it beautifully in a React application using a custom hook.

Local Storage Basics

Local storage is a part of the Web Storage API, we can use it directly without any setup. Here's how we can interact with local storage using JavaScript:

Setting an Item

We can set an Item using a key-value pair.

localStorage.setItem('username', 'Tommy');

Getting an Item

With the same key we saved earlier, we can use it to look it up.

const username = localStorage.getItem('username');
console.log(username); // Output: Tommy

Removing an Item

Similarly, this applies to removing items as well.

localStorage.removeItem('username');

Clearing All Items

This clears all keys and values from local storage.

localStorage.clear();

Creating a Custom Hook in React

Now that we've gone over the basics, let's create a custom hook to use in React.

To make local storage management more reusable and React-friendly, we can create a custom hook called useLocalStorage. This hook will handle setting, getting, and removing items seamlessly.

import { useState } from 'react';

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = localStorage.getItem(key);
      // Parse stored json or return initialValue
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  // Function to set value in state and local storage
  const setValue = (value) => {
    try {
      setStoredValue(value);
      localStorage.setItem(key, JSON.stringify(value));
    } catch (error) {
      console.error(error);
    }
  };

  // Function to remove item from local storage
  const removeValue = () => {
    try {
      localStorage.removeItem(key);
      // Reset state to initialValue
      setStoredValue(initialValue);
    } catch (error) {
      console.error(error);
    }
  };
  
  return [storedValue, setValue, removeValue];
}

To use the useLocalStorage hook:

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

function App() {
  const [name, setName, removeName] = useLocalStorage('name', 'Tommy');

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)} 
        placeholder="Enter your name"
      />
      <button onClick={removeName}>Remove Name</button>
    </div>
  );
}

export default App;