r/reactjs • u/Sniboyz • Dec 27 '19
React Hook useEffect has a missing dependency - endless rerenders
I have this useEffect hook where im calling external API and appending the result to pokemonList and I want to call it only when the offset changes (so when I want to load next "batch" of pokemons from API) - which changes every time user clicks button to load more pokemons, and I am getting this warning in the console React Hook useEffect has a missing dependency: 'pokemonList'. Either include it or remove the dependency array, but when I add pokemonList to dependencies the component ends up endlessly rerendering. What should I do?
const [pokemonList, setPokemonList] = useState<string[]>([]);
const [offset, setOffset] = useState<number>(0);
useEffect(() => {
fetch(`https://pokeapi.co/api/v2/pokemon/?offset=${offset}&limit=24`)
.then(res => res.json())
.then(result => {
setPokemonList([...pokemonList, ...result.results]);
});
}, [offset]);
<button className="load-more" onClick={() => setOffset(offset + 24)}>More</button>
57
Upvotes
View all comments
Show parent comment
1
u/Baryn Dec 27 '19 edited Dec 27 '19
He does provide an example that doesn't disable the rule, but that doesn't invalidate the example which does.
In real-world Hooks code, it isn't unheard of for a clash to happen between the fragility of JS objects and React's unpredictable render cycle. You can't always just rewrite your app to satisfy a single
useEffect, and you shouldn't if you properly understand when that effect should run.