useLocalStorage
A custom hook that provides functionalities for managing data in the browser's local storage.
Add hook
Create a file use-local-storage.ts
and copy & paste the code from useLocalStorage.
Hook
import { useEffect, useState } from 'react'
export type Item = string | number | object | null
export const useLocalStorage = (fn?: () => void) => {
const items = getLocalStorageItems()
const [storage, setStorage] = useState<{ [x: string]: Item }[]>(items)
useEffect(() => {
if (fn && typeof fn == 'function') {
fn()
}
}, [storage, fn])
const getValue = (itemKey: string) => {
const items = Object.values(storage)
for (const item of items) {
if (itemKey in item) {
return item[itemKey]
}
}
return null
}
const renameKey = (oldKey: string, newKey: string) => {
const item = checkItem(oldKey)
if (!item) {
throw new Error('This item does not exist in the local storage')
}
const value = localStorage.getItem(oldKey)
localStorage.removeItem(oldKey)
if (value) {
localStorage.setItem(newKey, value)
setStorage(getLocalStorageItems())
}
}
const getMultipleValues = (keys: string[]) => {
const multipleValues: string[] = []
keys.forEach(key => {
const value = getValue(key) as string
multipleValues.push(value)
})
return multipleValues
}
const addItem = (key: string, value: Item) => {
if (typeof value === 'object') {
localStorage.setItem(key, JSON.stringify(value))
}
if (typeof value === 'number') {
localStorage.setItem(key, value.toString())
}
if (typeof value === 'string') {
localStorage.setItem(key, value)
}
setStorage([...storage, { [key]: value }])
}
const addMultipleItems = (items: { key: string; value: string }[]) => {
for (const item of items) {
addItem(item.key, item.value)
}
}
const deleteItem = (key: string) => {
const item = checkItem(key)
if (!item) {
throw new Error('This item does not exist in the local storage')
}
if (item) {
localStorage.removeItem(key)
setStorage(getLocalStorageItems())
}
}
const deleteItemAfterDelay = (key: string, time: number) => {
setTimeout(() => {
deleteItem(key)
}, time)
}
const deleteMultipleItems = (keys: string[]) => {
keys.forEach(key => {
deleteItem(key)
})
}
const clearLocalStorage = () => {
localStorage.clear()
setStorage([])
}
return {
storage,
getValue,
getMultipleValues,
addItem,
addMultipleItems,
renameKey,
deleteItem,
deleteItemAfterDelay,
deleteMultipleItems,
clearLocalStorage,
}
}
export const checkItem = (key: string) => localStorage.getItem(key)
export const getLocalStorageItems = () => {
const items: { [x: string]: string | null }[] = []
const keys = Object.keys(localStorage)
keys.forEach(key => {
items.push({ [key]: localStorage.getItem(key) })
})
return items
}
Usage
import React, { useEffect } from 'react';
import { useLocalStorage } from './hooks/use-local-storage';
function App() {
const { storage, addItem, renameKey, getValue, deleteItem, deleteItemAfterDelay, clearLocalStorage } = useLocalStorage();
const handleNewItem = () => {
addItem('mode', 'dark');
};
const handleDeleteItem = () => {
deleteItem('mode');
};
const handleDeleteItemAfterDelay = () => {
deleteItemAfterDelay('color', 2000);
};
const handleRenameItem = () => {
renameKey('mode', 'color');
};
useEffect(() => {
clearLocalStorage();
}, []);
useEffect(() => {
console.log(storage);
}, [storage]);
useEffect(() => {
const retrievedValue = getValue('color');
console.log('Retrieved value:', retrievedValue);
}, [getValue]);
return (
<div>
<h1>Local Storage Demo</h1>
<button onClick={handleNewItem}>Add Item</button>
<button onClick={handleDeleteItem}>Delete Item</button>
<button onClick={handleRenameItem}>Rename Key</button>
<button onClick={handleDeleteItemAfterDelay}>Delete After 2s</button>
</div>
);
}
export default App;
API
Returns
Name | Description |
---|---|
storage | An array representing the current state of local storage items. |
getValue(itemKey: string): string | null | Retrieves the value of a specific item from local storage. |
renameKey(oldKey: string, newKey: string): void | Renames a key in the local storage. |
getMultipleValues(keys: string[]): string[] | Retrieves values for multiple items from local storage. |
addItem(key: string, value: string): void | Adds a new item to the local storage. |
addMultipleItems(items: { key: string; value: string }[]): void | Adds multiple items to the local storage. |
deleteItem(key: string): void | Deletes an item from the local storage. |
deleteItemAfterDelay(key: string, time: number): void | Deletes an item from the local storage after a specified delay. |
deleteMultipleItems(keys: string[]): void | Deletes multiple items from the local storage. |
clearLocalStorage(): void | Clears all items from the local storage. |