Skip to content

Instantly share code, notes, and snippets.

@alperkilickaya
Last active January 8, 2024 10:55
Show Gist options
  • Select an option

  • Save alperkilickaya/547a42b40e5ced6855b5225c7c75b14d to your computer and use it in GitHub Desktop.

Select an option

Save alperkilickaya/547a42b40e5ced6855b5225c7c75b14d to your computer and use it in GitHub Desktop.
custom react hook for calculating local storage size in kb.
import { useState, useEffect } from "react";
export function useLocalStorageSize() {
const [localStorageSize, setLocalStorageSize] = useState(0);
useEffect(() => {
const calculateLocalStorageSize = () => {
let totalSize = 0;
for (let key in localStorage) {
if (Object.prototype.hasOwnProperty.call(localStorage, key)) {
const size = (localStorage[key].length + key.length) * 2;
totalSize += size;
}
}
return totalSize / 1024; // Convert to kb
};
const updateLocalStorageSize = () => {
const size = calculateLocalStorageSize();
setLocalStorageSize(size);
};
// Listen for changes to storage event
window.addEventListener("storage", updateLocalStorageSize);
// Calculate initial size
updateLocalStorageSize();
// Cleanup
return () => {
window.removeEventListener("storage", updateLocalStorageSize);
};
}, []);
return `${localStorageSize} kb`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment