I'm learning ReactJS and Javascript, and I've occurred this problem, I don't know why it acts like that, but I think I know that my function is rendering too many times by setting the State for setEpisodeList over and over again I guess, how do I resolve this in my code?
The info state contains an episodes object that has an array type.
I have over 1000 episodes in 1 array, so I want to split that 1 big episodes array that contains over 1000 episodes into smaller chunks, each chunk will be an array that contains 10 episodes in it, that's why I'm using episodeListChunk.push(info.episodes.splice(0, 10)).
So it'll become
[
[chunk 1 - 10 episodes],
[chunk 2 - 10 episodes],
[chunk 3 - 10 episodes],
[chunk 4 - 10 episodes], ...
]
If I use console.log(episodeListChunk), I see it's working fine.
But if I'm setEpisodeList(episodeListChunk) then I get too many re-renders. Does that mean every time the while loop runs it'll setState every time? If that's so, which approach should I be doing to handle these situations?
Here's my code:
function MovieWatch({ instance }) {
const [info, setInfo] = useState([])
const [done, setDone] = useState(false)
const [episodeList, setEpisodeList] = useState([])
let { slug } = useParams()
const getInfo = async () => {
const { data } = await instance.get("/getInfo?slug=" + slug)
setInfo(data.data)
setDone(true)
}
useEffect(() => {
getInfo()
}, [])
const chunkEpisode = () => {
const episodeListChunk = []
while (info.episodes.length) {
episodeListChunk.push(info.episodes.splice(0, 10))
}
setEpisodeList(episodeListChunk)
}
return (
<>
<div>Hello info page</div>
{!done ? (
<Loading loading={true} background="#000000" loaderColor="#FFFF00" />
) : (
<>
{info ? chunkEpisode() : console.log("")}
<div>Done loading</div>
</>
)}
</>
)
}

