Skip to content

Commit af27cc3

Browse files
Merge pull request #126 from fredrikekelund/patch-1
Support server side rendering in useLocalStorage
2 parents 4f567da + 8a949cd commit af27cc3

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/pages/useLocalStorage.md

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)