UNPKG

react-reuse-hooks

Version:

A collection of 30+ production-ready reusable React hooks for web apps, covering state, effects, media, forms, and utilities.

23 lines (19 loc) 560 B
import { useState, useEffect } from "react"; export function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (err) { return initialValue; } }); useEffect(() => { try { localStorage.setItem(key, JSON.stringify(storedValue)); } catch (err) { console.error(err); } }, [key, storedValue]); return [storedValue, setStoredValue]; }