when Im using the useEffect hook with the setState hook, the state isn't updated if I only want the useEffect to run once (i.e. pass an empty array as the second parameter).
If i pass the array that Im updating as the second parameter, the state gets updated but then the useEffect keeps running in an infinite loop...
Here is the code that Im trying to run: In this example when printing out memes or endPage - they still hold their initial state values ([] and 0)
function ImageContainer() {
const [memes, setMemes] = useState([]);
const [currentIndex, setIndex] = useState(0);
const [currentPage, setPage] = useState(1);
const [endPage, setEndPage] = useState(0);
useEffect(() => {
getMemes(currentPage).then((data) => {
setEndPage(data.pagination.totalPages);
setMemes(data.data);
console.log(data);
console.log(memes);
console.log(endPage);
});
}, []);
but if I pass memes as the second parameter:
function ImageContainer() {
const [memes, setMemes] = useState([]);
const [currentIndex, setIndex] = useState(0);
const [currentPage, setPage] = useState(1);
const [endPage, setEndPage] = useState(0);
useEffect(() => {
getMemes(currentPage).then((data) => {
setEndPage(data.pagination.totalPages);
setMemes(data.data);
console.log(data);
console.log(memes);
console.log(endPage);
});
}, [memes]);
Then the console.log shows that both of the states have been updated, but the code keeps looping infinitely.
Thanks!
currentPage
instead of memes in the array as yourgetMemes
method seems to depend oncurrentPage
. If you passmemes
, it'll be stuck in an infinite loop – rishabh0211