I want to get data from my local storage and store it in state so I don't have to refresh my page every time I want to update table. Here is my code I know I am doing some mistake here because I am learning react.js. I get this warning every second hundreds of time "Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render."
const [items, setItems] = useState([]);
useEffect(() => {
const items = JSON.parse(localStorage.getItem("value"));
if (items) {
setItems(items);
}
}, [items]);
How do I solve this?
CodePudding user response:
The useEffect
function starts an infinite loop. It calls setItems
, but also depends on the items state so it sets the state indefinitely.
You can give useEffect
an empty dependency array so it sets the Items
only once on the first render.
const [items, setItems] = useState([]);
useEffect(() => {
const items = JSON.parse(localStorage.getItem("value"));
if (items) {
setItems(items);
}
}, []);
CodePudding user response:
First you shouldn't name your variables the same, it makes the code harder to read and it's prone to error.
Then the answer to your problem with the useEffect is in your statement. What makes a useEffect to re-render? A little bit more help, in JS does {} === {}?
Finally if you want to get what's in localstorage only when user log in or come back to the page it should only happen one time right?
Then you could have a event handler that adds to the state and updates the local storage with the new state (you have more than one option here). Don't forget to clean the localstorage though in the case the user doesn't need persistence anymore.