'setState in useEffect with that state as dependency
I have A parent component with a child modal component. the parent component has a blank state variable passed down to child. the parent component also has a div that needs editorState initialized on render to work properly. My child component has a button that sets stateForDiv with some data to render in parent components div. I need parent component to setEditorState when child updates stateForDiv. Naturally I tried to use useEffect with stateForDiv as dependency. Well when the useEffect runs it creates and infinite loop when I run setEditorState. How can I set EditorState every time the stateForDiv changes without creating an infinite loop?
import React, {useState, useEffect} from 'react';
import {convertFromRaw, EditorState } from 'draft-js';
import ChildComponent from './ChildComponent';
const ParentComponent = () => {
const [ editorState, setEditorState ] = useState(() => { return EditorState.createEmpty()}) // this must be initialized once on render
const [ stateForDiv, setStateForDiv ] = useState() // this state is passed down to child component, when the child component updates this state, we need to setEditorState.. this is my problem, infinite loop in useEffect when using stateForDiv as dependency
useEffect(() => {
if(stateForDiv) {
setEditorState(EditorState.createWithContent(
convertFromRaw(stateForDiv)));
} else {
console.log("false")
}
}, [stateForDiv])
return (
<div currentContent={editorState} onChange={setEditorState} >
</div>
<div>
<Modal>
<ChildComponent setStateForDiv={setStateForDiv}
</Modal>
</div>
Child component that is setting state for stateForDiv
const ChildComponent = ({setStateForDiv}) => {
return (
<div>
<button onClick={() => {setStateForDiv("<p>hi there</p>")} } ></button>
</div>
)
}
Solution 1:[1]
First point, const [ stateForDiv, setStateForDiv ] = useState() this statement is not required. Beacause you just want <ChildComponent /> component which onClick event to control <div currentContent={editorState} > component display. You can <ChildComponent onClick={setEditorState(EditorState.createWithContent(convertFromRaw("<p>hi there</p>")));}/>.
In addition, why your useEffect infinite loop.As your useEffect dependence is wrong.So you should take care how to use dependence.
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 | Jack.KC.Wong |
