import { useState , useEffect } from 'react' ; export function useLocalStorage < T > ( key , defaultValue ) { const [ item , setItem ] = useState < T > ( getFromStorage ( key , defaultValue ) ) ; const updateFromStorage = ( ) => { const storedItem = getFromStorage ( key , defaultValue ) ; setItem ( storedItem ) ; } ; const saveToStorage = ( value ) => { if ( value === undefined ) { window . localStorage . removeItem ( key ) ; } else { window . localStorage . setItem ( key , JSON . stringify ( value ) ) ; updateFromStorage ( ) ; } } ; useEffect ( ( ) => { window . addEventListener ( 'storage' , ( event ) => { if ( event . key === key ) { updateFromStorage ( ) ; } } ) ; } , [ ] ) ; useEffect ( ( ) => { setItem ( getFromStorage ( key , defaultValue ) ) ; } , [ key , defaultValue ] ) ; return [ item , saveToStorage ] as const ; } function getFromStorage < T > ( keyName , defaultValue ) { const storedItem = window . localStorage . getItem ( keyName ) ; if ( storedItem !== null ) { try { return JSON . parse ( storedItem ) as T ; } catch ( err ) { window . localStorage . removeItem ( keyName ) ; console . log ( `Unable to decode: ${ keyName }` ) ; } } return defaultValue ; }