Bug: Warning: Cannot update a component (`Parent`) while rendering a different component (`Child`)
aliveli186 opened this issue · comments
aliveli186 commented
I'm receiving that error when the page is being rendered without even clicking the link to trigger the state change.
Here is the simplified code:
import React, { useState } from "react"
export default function Parent() {
const [itemId, setItemId] = useState(0);
return (
<Child setItemId={setItemId} />
);
}
export function Child({ setItemId }) {
return (
<a onClick={setItemId(1)} />
);
}
Sebastian "Sebbie" Silbermann commented
<a onClick={setItemId(1)} />
this means that you will call setItemId
when rendering which triggers the warning. You probably want to write
export function Child({ setItemId }) {
return (
- <a onClick={setItemId(1)} />
+ <a onClick={() => setItemId(1)} />
);
}
aliveli186 commented
<a onClick={setItemId(1)} />
this means that you will callsetItemId
when rendering which triggers the warning. You probably want to writeexport function Child({ setItemId }) { return ( - <a onClick={setItemId(1)} /> + <a onClick={() => setItemId(1)} /> ); }
Yes, I was just going to write wrapping it inside a function solved the issue.