import { useState } from "react" ; type Callback < T > = ( value : T ) => T ; export default < T > ( key , defaultValue ) : [ T , ( value : T | Callback < T > ) => void ] => { const storage = typeof window !== "undefined" && window . localStorage ; const [ storedValue , setStoredValue ] = useState < T > ( ( ) => { if ( ! storage ) return defaultValue ; try { const item = storage . getItem ( key ) ; return item ? JSON . parse ( item ) : defaultValue ; } catch ( error ) { console . error ( error ) ; return defaultValue ; } } ) ; const setValue = ( value ) => { try { const valueToStore = value instanceof Function ? value ( storedValue ) : value ; setStoredValue ( valueToStore ) ; storage && storage . setItem ( key , JSON . stringify ( valueToStore ) ) ; } catch ( error ) { console . error ( error ) ; } } ; return [ storedValue , setValue ] ; } ;