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.
Creating the useLocalStorage Custom Hook
Let's create the useLocalStorage custom hook that will handle the local storage operations.
- In your project directory, navigate to the src folder.
- Create a new folder called hooks, and inside that folder, create a new file called useLocalStorage.js
- 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];
}
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);
Contributions are welcome! If you find any issues or have suggestions for improvements, please create an issue or submit a pull request.
This project is owned by Patrick Rayner, if you have any questions please, ask me.