Files
traque/traque-front/hook/useLocalStorage.jsx
Sébastien Rivière d25dcfcbc1 Corrections
2025-06-25 17:52:59 +02:00

30 lines
884 B
JavaScript

"use client";
import { useEffect, useState } from "react";
export default function useLocalStorage(key, initialValue) {
const [storedValue, setStoredValue] = useState(initialValue);
const [loading, setLoading] = useState(true);
useEffect(() => {
try {
const item = window.localStorage.getItem(key);
setStoredValue(item ? JSON.parse(item) : initialValue);
} catch (error) {
console.log(error);
}
setLoading(false);
}, []);
const setValue = value => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setStoredValue(valueToStore);
window.localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
}
return [storedValue, setValue, loading];
}