React child component to parent component useState rewrite warning

Asked 2 years ago, Updated 2 years ago, 51 views

For those who know how to fix the useState rewrite warning from child components in React:
I would appreciate it if you could let me know.

The execution screen does not fail, but when I open the console, a warning appears.I would like to correct this.
Console Warning Statements

Warning: Cannot update a component(`App`) while rendering a different component(`Child`).Tolocate the bad setState() call inside `Child`, follow the stack trace as described

React 17.0.2.
The following code
Parent Components

import React, {useState} from 'react';
import {Child} from './Child.js';

constApp=()=>{
const [child, setChild] = useState("");
return(
<div>
 <Child test={setChild}/>
 {child}
</div>
);
}
export default App;

Child Components

const Child=(props)=>{
const message="Hello World"
return(
<p>{props.test(message)}</p>
)
}
export default Child; 

reactjs

2022-09-30 20:22

1 Answers

I didn't know exactly what I wanted to do from the code in the questionnaire, but the cause and response of the error can be found in the official blog.

React components must not cause side effects to other components during rendering.

Calling setState during a render is supported, but only for the same component.
(omitted)
In rare cases where you want to intentionally change the state of other components as a result of a render, you can wrap the setState call to useEffect.

useEffect means the following implementation:

import {useEffect} from "react";

const Child=({test})=>{
  const message = "Hello World";
  useEffect()=>test(message), [test]);
  return<p></p>;
};
export default Child;

(As stated in the "Rare Case", I think that the implementation of this method itself is often wrong.)


2022-09-30 20:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.