I have the following custom hook which stores data in the localstorage:
import { useCallback, useEffect, useState } from "react";
export const useLocalStorage = (key, initialValue) => {
const initialize = (key) => {
try {
const item = localStorage.getItem(key);
if (item && item !== "undefined") {
return JSON.parse(item);
}
localStorage.setItem(key, JSON.stringify(initialValue));
return initialValue;
} catch {
return initialValue;
}
};
const [state, setState] = useState(() => initialize(key)); // problem is here
const setValue = useCallback(
(value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setState(valueToStore);
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
},
[key, setState]
);
const remove = useCallback(() => {
try {
localStorage.removeItem(key);
} catch {
console.log(error);
}
}, [key]);
return [state, setValue, remove];
};
It shows the following problem, which i googled it and it seems it due to the fact that Nextjs tries to run the code on the server side and there is no available window object.
The problem seems to come from the line where i try to initialize the stored data:
const [state, setState] = useState(() => initialize(key));
I tried to pack this logic within a useEffect so it only runs on client side, but i got the infinite loop which i couldnt solve.
React Hook useEffect has missing dependencies: 'initialize' and 'key'.
So when i add initialzie method to the depenedncy, it says that the initialize method should use useCallback, so than i made it using that. When i add initialValue to the dependency array of useCallback, i got infinite loop. – Occlusive