In many of my components, I have to use token from store to get data and represent it (header menu, footer menu, products on page, slider images, etc.). What I am trying to do is to get this data only if I don't have it, but React keeps sending requests every time token changes (as token is dependency), even though I clearly put condition and I can see it if I console.log it. What am I doing wrong?
const [cities, setCities] = useState([]); useEffect(() => { if (!cities.length) { fetch(`.....&token=${props.token}`) .then(response => response.json()) .then(data => { if (data.data.results) { setCities(data.data.results.cities) } }) } }, [props.token, cities.length]);
citieson every re-render,citiesis always a new object, thuscities.lengthis not the same as the previous one. Alsoif(!cities.length)is always true sincecitiesis always defined, initially the length is0, which still returns true. What you could do instead isif(cities.length<1)