diff --git a/.changeset/clever-mice-search.md b/.changeset/clever-mice-search.md new file mode 100644 index 0000000000..4fd5b49659 --- /dev/null +++ b/.changeset/clever-mice-search.md @@ -0,0 +1,5 @@ +--- +"@tiptap/react": patch +--- + +Fixes strict mode accidentally destroying the editor instance diff --git a/demos/src/Examples/Performance/React/index.jsx b/demos/src/Examples/Performance/React/index.jsx index b68b18cdce..4dce96ff95 100644 --- a/demos/src/Examples/Performance/React/index.jsx +++ b/demos/src/Examples/Performance/React/index.jsx @@ -93,7 +93,7 @@ function EditorInstance({ shouldOptimizeRendering }) { ) } -export default () => { +const EditorControls = () => { const [shouldOptimizeRendering, setShouldOptimizeRendering] = React.useState(true) return ( @@ -128,3 +128,11 @@ export default () => { ) } + +export default () => { + return ( + + + + ) +} diff --git a/packages/react/src/useEditor.ts b/packages/react/src/useEditor.ts index d6abca92d8..5df40e60ca 100644 --- a/packages/react/src/useEditor.ts +++ b/packages/react/src/useEditor.ts @@ -57,6 +57,7 @@ export function useEditor( options: UseEditorOptions = {}, deps: DependencyList = [], ): Editor | null { + const isMounted = useRef(false) const [editor, setEditor] = useState(() => { if (options.immediatelyRender === undefined) { if (isSSR || isNext) { @@ -220,12 +221,21 @@ export function useEditor( * only be called when the component is removed from the DOM, since it has no deps. * */ useEffect(() => { + isMounted.current = true return () => { + isMounted.current = false if (editor) { // We need to destroy the editor asynchronously to avoid memory leaks // because the editor instance is still being used in the component. - setTimeout(() => (editor.isDestroyed ? null : editor.destroy())) + setTimeout(() => { + // re-use the editor instance if it hasn't been destroyed yet + // and the component is still mounted + // otherwise, asynchronously destroy the editor instance + if (!isMounted.current && !editor.isDestroyed) { + editor.destroy() + } + }) } } }, [])