console.log of editorState on unfocus display a stack of all the changes

Viewed 67

Please check in first place this codesandbox.

I wrote a TextEditor component using draftjs that get 3 props:

  • text: html as a string
  • onChange: a callback that get a unique parameter (the updated html string)
  • onUnfocus: a callback that is called when you click outside of the TextEditor

If you look in the App component where I use my TextEditor component, I store the text in a state that I update using onChange.

Clicking outside the TextEditor (with the blue background) will trigger the onUnfocus function that console.log the text state.

But If I write a word (let's say Hello) and then click outside the TextEditor I will get so many console.log as changes:

> H
> He
> Hel
> Hell
> Hello

The expected behavior would be to have a single console.log with the latest changes:

> Hello

Has someone an idea why I get so many console.log?

1 Answers

The issue is that you forgot to return your useEffect helper, and also didn't pass in text as a dependency, so the cleanup code is never called, so each time it renders it adds another document.addEventListener without ever removing the previous.

React.useEffect(() => {
  return onClickOutsideHook( // add return here
    editorRef,
    (): void => {
      if (isFocus && onUnfocus !== undefined) {
        onUnfocus();
      }

      setIsFocus(false);
    }
  );
}, [editorState, isFocus, onUnfocus, text]); // add text as dependency
Related