'Why I'm getting - Rendered more hooks than during the previous render
I have a hook named useComments.
When I hardcode,
const { comments1 } = useComments(requests[l].id, true);
const { comments2 } = useComments(requests[l].id, true);
const { comments3 } = useComments(requests[l].id, true);
I'm getting desired output.
But When I use for loop for getting ID stored in an array I'm getting 'Rendered more hooks than during the previous render.' Error.
for (let l = 0; l < 2; l++) {
const { comments } = useComments(requests[l].id, true);
console.log({ [l]: comments });
}
Solution 1:[1]
This is a limitation on React hooks and happens because the number of hooks inside a single component before return must be constant.
What you can do - just break it up into a component that has a constant number of hooks - just one:
function Comments({ requestId }) {
const { comments } = useComments(requestId, true);
console.log({ [l]: comments });
return null
}
function Wrapper() {
const requestIds = []
for (let l = 0; l < 2; l++) {
requestIds.push(requests[l].id)
}
// note we don't use any hooks here.
return requestIds.map((requestId) => <Comments requestId={requestId} />
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Silviu-Marian |
