jpuri / html-to-draftjs

MIT License
161 stars 104 forks source link

Infinite Loop in functional component #71

Open invious opened 4 years ago

invious commented 4 years ago
const ArticleForm = (props) => {

    const {article} = props
    const classes = useStyles();
    const dispatch = useDispatch()
    const router = useRouter()

    const [editorState, setEditorState] = useState(EditorState.createEmpty());

    const blocksFromHtml = htmlToDraft(article.body);
    const { contentBlocks, entityMap } = blocksFromHtml;
    const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
    const loadedEditorState= EditorState.createWithContent(contentState);

    debugger

    setEditorState(loadedEditorState)

the setEditorState is causing this error:

image

ilyador commented 4 years ago

useState sets an initial state, and setEditorState changes it right after. State change causes the component to re-render, and once it is rendered again, the state is changed again putting it in an infinite re-render loop.

You need to use useEffect to make sure your state change runs before the component is mounted. preventing another render.