I have that problem, I have 3 componeents : App, C1, C2 and I am trying to pass a variable from App to C2 through C1.
Here is App.js :
import { useState } from "react";
import "./styles.css";
import C1 from "./C1";
const App = () =>{
const [myVar, setMyVar] = useState("")
return(
<>
<h1>Test</h1>
<C1 myVar={myVar} setMyVar={(test) => {setMyVar(test)}} />
</>
)
}
export default App
Here is C1.js :
import C2 from "./C2";
const C1 = (props) => {
console.log(props.myVar);
//props.setMyVar("Hola")
console.log(props.myVar);
return (
<>
<h1>Hello</h1>
<C2
myVar={props.myVar}
setMyVar={(test) => {
props.setMyVar(test);
}}
/>
</>
);
};
export default C1;
and the last C2.js :
const C2 = (props) =>{
console.log(props.myVar)
props.setMyVar("Manger")
console.log(props.myVar)
return(
<h1>Easy</h1>
);
}
export default C2;
But I saw in the console the following error :
Warning: Cannot update a component (
App) while rendering a different component (
C2). To locate the bad setState() call inside
C2, follow the stack trace as described in https://reactjs.org/link/setstate-in-render C2@https://jnulps.csb.app/src/C2.js:13:3 C1@https://jnulps.csb.app/src/C1.js:17:3 App@https://jnulps.csb.app/src/App.js:26:41
Here is the full project : The full code
Could you help me please ?
Thank you very much !
CodePudding user response:
Because in C2.js you setState through props.setMyVar("Manger")
is reason to make React infinite render at the same time when state change, to fix it put props.setMyVar("Manger")
inside useEffect():
const C2 = (props) =>{
console.log(props.myVar)
useEffect(() => {
props.setMyVar("Manger")
}, [])
console.log(props.myVar)
return(
<h1>Easy</h1>
);
}
export default C2;
CodePudding user response:
The error message will be displayed if parent (App) states are set while rendering children (C2).
Specifically, while trying to render C2, React will run props.setState("Manger")
which will also trigger a re-render of App. One way to fix this is to put props.setState("manger")
of C2 inside a useEffect
, or put it in some element's on-click handler (if you have a specific use case).
Another thing to note is that, console.log
right after setState
will not get you the most updated value, because setState
is asynchronous