UNPKG

useful-custom-react-hooks

Version:

A collection of useful custom React hooks to simplify common tasks and enhance your React applications.

23 lines (22 loc) 778 B
import { useEffect, useState } from 'react'; export const useStorage = (key, initialState) => { var _a; const [storageData, setStorageData] = useState(JSON.parse((_a = localStorage.getItem(key)) !== null && _a !== void 0 ? _a : null)); const setData = (value) => { if (value === null) { localStorage.removeItem(key); setStorageData(null); } else if (value) { localStorage.setItem(key, JSON.stringify(value)); setStorageData(value); } }; useEffect(() => { if (storageData === null && initialState) { localStorage.setItem(key, JSON.stringify(initialState)); setStorageData(initialState); } }, []); return [storageData, setData]; };