Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

useSessionStorage.tsx

14 lines369 Bytes

1import * as React from 'react'
2​
3export function useSessionStorage<T>(key: string, initialValue: T) {
4 const state = React.useState<T>(() => {
5 const stored = sessionStorage.getItem(key)
6 return stored ? JSON.parse(stored) : initialValue
7 })
8​
9 React.useEffect(() => {
10 sessionStorage.setItem(key, JSON.stringify(state[0]))
11 }, [state[0]])
12​
13 return state