Skip to content

useLocalStorage

Store, retrieve, and synchronize data from the browser’s localStorage API with useLocalStorage

Installation

Copy and paste the following code into your project.

use-local-storage.jsx
import { useCallback, useState } from "react";
export const useLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = useCallback(
(value) => {
try {
setStoredValue(value);
const stringifiedValue = JSON.stringify(value);
window.localStorage.setItem(key, stringifiedValue);
} catch (error) {
console.error(error);
}
},
[key]
);
return [storedValue, setValue];
};

Usage

import { useLocalStorage } from "@/hooks/use-local-storage";
const [text, setText] = useLocalStorage("text", "");

API

Parameters

NameTypeDescription
keystringThe key to store the value under. It should be unique to avoid collisions with other libraries or components.
initialValueanyThe default value to use if nothing is stored in localStorage.

Return value

NameTypeDescription
valueanyThe value stored in local storage. If nothing is stored, the initial value is returned.
setValue(value: any) => voidA function to set the value in local storage. This function will also persist the value to local storage.