Skip to content

Instantly share code, notes, and snippets.

@patrick-rayner
Last active May 19, 2023 13:00
Show Gist options
  • Save patrick-rayner/3eec6b73bb9158c0a72f755b668e09d6 to your computer and use it in GitHub Desktop.
Save patrick-rayner/3eec6b73bb9158c0a72f755b668e09d6 to your computer and use it in GitHub Desktop.
useLocalStorage Custom Hook

useLocalStorage - Custom Hook

A custom React hook that allows you to store and retrieve data in the browser's local storage.

🔧 Step 1

Setting up a React Project

Before we can use the useLocalStorage hook, let's set up a basic React project. If you already have a React project, you can skip this step.

🔧 Step 2

Creating the useLocalStorage Custom Hook

Let's create the useLocalStorage custom hook that will handle the local storage operations.

  1. In your project directory, navigate to the src folder.
  2. Create a new folder called hooks, and inside that folder, create a new file called useLocalStorage.js
  3. Open useLocalStorage.js in your preferred code editor, and paste the following code:
import { useState, useEffect } from 'react';

export default function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      // Try to retrieve the item from local storage with the given key
      const item = localStorage.getItem(key);
      // If the item exists, parse and return its JSON value
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error('Error retrieving data from local storage:', error);
      // If there is an error, return the initial value
      return initialValue;
    }
  });

  const setValue = (value) => {
    try {
      // Store the value as a JSON string in local storage under the given key
      localStorage.setItem(key, JSON.stringify(value));
      // Update the storedValue state variable with the new value
      setStoredValue(value);
    } catch (error) {
      console.error('Error storing data in local storage:', error);
    }
  };

  const clearValue = () => {
    try {
      // Remove the item from local storage with the given key
      localStorage.removeItem(key);
      // Reset the storedValue state variable to the initial value
      setStoredValue(initialValue);
    } catch (error) {
      console.error('Error clearing data from local storage:', error);
    }
  };

  useEffect(() => {
    try {
      // Store the current value of storedValue in local storage whenever it changes
      localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error('Error storing data in local storage:', error);
    }
  }, [key, storedValue]);

  // Return the stored value, setValue function, and clearValue function as an array
  return [storedValue, setValue, clearValue];
}

🔧 Step 3

Using the useLocalStorage Custom Hook

Let's import the hook into your component:

    import useLocalStorage from '../hooks/useLocalStorage';

Initialize the hook in your component:

   const [storedValue, setValue, clearValue] = useLocalStorage(key, initialValue);
  • key (string): The key to store the value in the local storage.
  • initialValue (any): The initial value to use if the key doesn't exist in the local storage.

Access the stored value and update it as needed:

// Get the stored value
console.log(storedValue);

// Set a new value
setValue(newValue);

// Clear the stored value
clearValue(key);

Contributing

Contributions are welcome! If you find any issues or have suggestions for improvements, please create an issue or submit a pull request.

License

This project is owned by Patrick Rayner, if you have any questions please, ask me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment