facebook / react

The library for web and native user interfaces.

Home Page:https://react.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug: Warning: Cannot update a component (`Parent`) while rendering a different component (`Child`)

aliveli186 opened this issue · comments

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)} />
    );
}

<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)} />
     );
  }

<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)} />
     );
  }

Yes, I was just going to write wrapping it inside a function solved the issue.