@@ -40,6 +40,10 @@ function useLocalStorage(key, initialValue) {
40
40
// State to store our value
41
41
// Pass initial state function to useState so logic is only executed once
42
42
const [storedValue , setStoredValue ] = useState (() => {
43
+ if (typeof window === " undefined" ) {
44
+ return initialValue;
45
+ }
46
+
43
47
try {
44
48
// Get from local storage by key
45
49
const item = window .localStorage .getItem (key);
@@ -62,7 +66,9 @@ function useLocalStorage(key, initialValue) {
62
66
// Save state
63
67
setStoredValue (valueToStore);
64
68
// 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
+ }
66
72
} catch (error) {
67
73
// A more advanced implementation would handle the error case
68
74
console .log (error);
@@ -98,6 +104,10 @@ function useLocalStorage<T>(key: string, initialValue: T) {
98
104
// State to store our value
99
105
// Pass initial state function to useState so logic is only executed once
100
106
const [storedValue, setStoredValue] = useState <T >(() => {
107
+ if (typeof window === " undefined" ) {
108
+ return initialValue ;
109
+ }
110
+
101
111
try {
102
112
// Get from local storage by key
103
113
const item = window .localStorage .getItem (key );
@@ -120,7 +130,9 @@ function useLocalStorage<T>(key: string, initialValue: T) {
120
130
// Save state
121
131
setStoredValue (valueToStore );
122
132
// 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
+ }
124
136
} catch (error ) {
125
137
// A more advanced implementation would handle the error case
126
138
console .log (error );
0 commit comments