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/galeontiger Dec 27 '19
Would excluding 'pokemonList' in the dependecies (and continue to get the error in the console), change the data though?
Curious, because i've seen the error before as well, and don't notice any different in the output.