@@ -40,6 +40,10 @@ function useLocalStorage(key, initialValue) {
4040 // State to store our value
4141 // Pass initial state function to useState so logic is only executed once
4242 const [storedValue , setStoredValue ] = useState (() => {
43+ if (typeof window === " undefined" ) {
44+ return initialValue;
45+ }
46+
4347 try {
4448 // Get from local storage by key
4549 const item = window .localStorage .getItem (key);
@@ -62,7 +66,9 @@ function useLocalStorage(key, initialValue) {
6266 // Save state
6367 setStoredValue (valueToStore);
6468 // Save to local storage
65- window .localStorage .setItem (key, JSON .stringify (valueToStore));
69+ if (typeof window !== " undefined" ) {
70+ window .localStorage .setItem (key, JSON .stringify (valueToStore));
71+ }
6672 } catch (error) {
6773 // A more advanced implementation would handle the error case
6874 console .log (error);
@@ -98,6 +104,10 @@ function useLocalStorage<T>(key: string, initialValue: T) {
98104 // State to store our value
99105 // Pass initial state function to useState so logic is only executed once
100106 const [storedValue, setStoredValue] = useState <T >(() => {
107+ if (typeof window === " undefined" ) {
108+ return initialValue ;
109+ }
110+
101111 try {
102112 // Get from local storage by key
103113 const item = window .localStorage .getItem (key );
@@ -120,7 +130,9 @@ function useLocalStorage<T>(key: string, initialValue: T) {
120130 // Save state
121131 setStoredValue (valueToStore );
122132 // Save to local storage
123- window .localStorage .setItem (key , JSON .stringify (valueToStore ));
133+ if (typeof window !== " undefined" ) {
134+ window .localStorage .setItem (key , JSON .stringify (valueToStore ));
135+ }
124136 } catch (error ) {
125137 // A more advanced implementation would handle the error case
126138 console .log (error );
0 commit comments