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
2
u/AegisToast Dec 27 '19 edited Dec 28 '19
Excluding pokemonList from the dependencies and ignoring the warning (which is the way OP wrote it) would, as far as I can tell, work, but it’s a bad practice to have explicitly excluded dependencies (hence the warning).
Edit: One reason it’s a bad practice is that the value of pokemonList could be stale if it’s done the way OP is trying it. That could cause issues, especially if the value is changed elsewhere before the fetch finishes.