11// Reference: https://usehooks.com/useLocalStorage/
22
33import { useQuery , useQueryClient } from '@tanstack/react-query'
4- import { Dispatch , SetStateAction , useCallback , useState , useEffect } from 'react'
4+ import { Dispatch , SetStateAction , useCallback , useState } from 'react'
55
66export function useLocalStorage < T > ( key : string , initialValue : T ) {
77 // State to store our value
@@ -58,39 +58,25 @@ export function useLocalStorageQuery<T>(key: string, initialValue: T) {
5858 const queryClient = useQueryClient ( )
5959 const queryKey = [ 'localStorage' , key ]
6060
61- // During SSR, return initial value immediately to prevent hydration mismatch
62- const [ isClient , setIsClient ] = useState ( false )
63-
64- useEffect ( ( ) => {
65- setIsClient ( true )
66- } , [ ] )
67-
6861 const {
6962 error,
7063 data : storedValue = initialValue ,
7164 isSuccess,
7265 isLoading,
7366 isError,
74- } = useQuery (
75- queryKey ,
76- ( ) => {
77- if ( typeof window === 'undefined' ) {
78- return initialValue
79- }
67+ } = useQuery ( queryKey , ( ) => {
68+ if ( typeof window === 'undefined' ) {
69+ return initialValue
70+ }
8071
81- const item = window . localStorage . getItem ( key )
72+ const item = window . localStorage . getItem ( key )
8273
83- if ( ! item ) {
84- return initialValue
85- }
86-
87- return JSON . parse ( item ) as T
88- } ,
89- {
90- enabled : isClient , // Only run query on client side
91- staleTime : Infinity , // Prevent unnecessary refetches
74+ if ( ! item ) {
75+ return initialValue
9276 }
93- )
77+
78+ return JSON . parse ( item ) as T
79+ } )
9480
9581 const setValue : Dispatch < SetStateAction < T > > = ( value ) => {
9682 const valueToStore = value instanceof Function ? value ( storedValue ) : value
@@ -103,8 +89,5 @@ export function useLocalStorageQuery<T>(key: string, initialValue: T) {
10389 queryClient . invalidateQueries ( queryKey )
10490 }
10591
106- // Return initial value during SSR, actual value on client
107- const finalValue = isClient ? storedValue : initialValue
108-
109- return [ finalValue , setValue , { isSuccess, isLoading, isError, error } ] as const
92+ return [ storedValue , setValue , { isSuccess, isLoading, isError, error } ] as const
11093}
0 commit comments