import { useCallback } from 'react' ; import { useState } from 'react' ; import { useMount } from '../useMount' ; export type UseSessionStorageOptions = { default serialize : ( value : unknown ) => string ; default deserialize : ( value : string ) => unknown ; } ; param key param initialValue param options see https export function useSessionStorage < T > ( key , initialValue , options ? ) { const [ storedValue , setStoredValue ] = useState ( initialValue ) ; const { deserialize = JSON . parse , serialize = JSON . stringify } = options || { } ; useMount ( ( ) => { try { const item = sessionStorage . getItem ( key ) ; item && setStoredValue ( deserialize ( item ) ) ; } catch ( error ) { console . error ( error ) ; } } ) ; const setValue = useCallback ( ( value ) => { try { setStoredValue ( value ) ; sessionStorage . setItem ( key , serialize ( value ) ) ; } catch ( error ) { console . error ( error ) ; } } , [ key , serialize ] ) ; return [ storedValue , setValue ] ; }