-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
fix(react): onCreate fired twice under React.StrictMode in useEditor #8095
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
a-y-ibrahim
wants to merge
7
commits into
ueberdosis:main
Choose a base branch
from
a-y-ibrahim:fix/react-strictmode-double-oncreate
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
1f9ca89
fix(react): prevent onCreate firing twice for StrictMode duplicate
a-y-ibrahim beef6fb
fix(react): simplify StrictMode duplicate fix to a guarded useRef
a-y-ibrahim 5227c55
test(react): add explicit non-StrictMode regression check for useEditor
a-y-ibrahim c08706d
fix(react): make the StrictMode fix work on React 18, not just 19
a-y-ibrahim 0a72984
test(react): lock in that a throwing onCreate doesn't crash the render
a-y-ibrahim 6abfc27
test(react): assert exactly one caught error for the onCreate-throw test
a-y-ibrahim 08906c6
test(react): cover onCreate correctness across deps-driven recreation
a-y-ibrahim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| '@tiptap/react': patch | ||
| --- | ||
|
|
||
| Fix `useEditor` firing `onCreate` twice for two different `Editor` instances under React StrictMode. `useEditor`'s `useState` lazy initializer is invoked twice by StrictMode for a single mount, and both calls construct (and auto-mount) a real `Editor`, so both used to schedule their own `create` event. `onCreate` is now buffered until the owning instance is confirmed mounted (i.e. its render effect actually runs) and only forwarded then - an instance whose effect never runs (the discarded one) never forwards it. Verified against React 18.2.0, 18.3.1, and 19.1.0. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,321 @@ | ||
| import { Document } from '@tiptap/extension-document' | ||
| import { Paragraph } from '@tiptap/extension-paragraph' | ||
| import { Text } from '@tiptap/extension-text' | ||
| import { render } from '@testing-library/react' | ||
| import React from 'react' | ||
| import { afterEach, describe, expect, it } from 'vitest' | ||
|
|
||
| import type { Editor } from '@tiptap/core' | ||
| import { useEditor } from './useEditor.js' | ||
|
|
||
| function flushTimers(ms: number) { | ||
| return new Promise<void>(resolve => { | ||
| setTimeout(resolve, ms) | ||
| }) | ||
| } | ||
|
|
||
| describe('useEditor', () => { | ||
| afterEach(() => { | ||
| document.body.innerHTML = '' | ||
| }) | ||
|
|
||
| it('does not fire onCreate more than once for a single mount under StrictMode', async () => { | ||
| // onBeforeCreate legitimately still fires for both the kept and the | ||
| // discarded StrictMode-duplicate instance (it fires synchronously as | ||
| // part of construction itself, before there's any way to know which one | ||
| // survives). onCreate is what's actually fixed here: it's deferred until | ||
| // the instance is confirmed mounted, so only the kept instance's onCreate | ||
| // is ever forwarded to the user's callback. | ||
| let beforeCreateCount = 0 | ||
| let createCount = 0 | ||
| const createdEditors = new Set<Editor>() | ||
| let latestEditor: Editor | null = null | ||
|
|
||
| function TestComponent() { | ||
| const editor = useEditor({ | ||
| extensions: [Document, Text, Paragraph], | ||
| onBeforeCreate: () => { | ||
| beforeCreateCount += 1 | ||
| }, | ||
| onCreate: ({ editor: createdEditor }) => { | ||
| createCount += 1 | ||
| createdEditors.add(createdEditor) | ||
| }, | ||
| }) | ||
|
|
||
| latestEditor = editor | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| const { unmount } = render( | ||
| React.createElement(React.StrictMode, null, React.createElement(TestComponent)), | ||
| ) | ||
|
|
||
| // The editor's own 'create' event fires via an internal setTimeout(0); | ||
| // give it real wall-clock time to flush. | ||
| await flushTimers(100) | ||
|
|
||
| expect(beforeCreateCount).toBeGreaterThanOrEqual(1) | ||
| expect(createCount).toBe(1) | ||
| expect(createdEditors.size).toBe(1) | ||
| expect(latestEditor?.isDestroyed).toBe(false) | ||
|
|
||
| unmount() | ||
| }) | ||
|
|
||
| it('still fires onCreate exactly once when mounted without StrictMode', async () => { | ||
| let createCount = 0 | ||
|
|
||
| function TestComponent() { | ||
| useEditor({ | ||
| extensions: [Document, Text, Paragraph], | ||
| onCreate: () => { | ||
| createCount += 1 | ||
| }, | ||
| }) | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| const { unmount } = render(React.createElement(TestComponent)) | ||
|
|
||
| await flushTimers(100) | ||
|
|
||
| expect(createCount).toBe(1) | ||
|
|
||
| unmount() | ||
| }) | ||
|
|
||
| it('keeps two sibling editors independent under StrictMode', async () => { | ||
| let createCountA = 0 | ||
| let createCountB = 0 | ||
| const createdA = new Set<Editor>() | ||
| const createdB = new Set<Editor>() | ||
| let editorA: Editor | null = null | ||
| let editorB: Editor | null = null | ||
|
|
||
| function ComponentA() { | ||
| const editor = useEditor({ | ||
| extensions: [Document, Text, Paragraph], | ||
| onCreate: ({ editor: e }) => { | ||
| createCountA += 1 | ||
| createdA.add(e) | ||
| }, | ||
| }) | ||
|
|
||
| editorA = editor | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| function ComponentB() { | ||
| const editor = useEditor({ | ||
| extensions: [Document, Text, Paragraph], | ||
| onCreate: ({ editor: e }) => { | ||
| createCountB += 1 | ||
| createdB.add(e) | ||
| }, | ||
| }) | ||
|
|
||
| editorB = editor | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| const { unmount } = render( | ||
| React.createElement( | ||
| React.StrictMode, | ||
| null, | ||
| React.createElement(ComponentA), | ||
| React.createElement(ComponentB), | ||
| ), | ||
| ) | ||
|
|
||
| await flushTimers(100) | ||
|
|
||
| expect(createCountA).toBe(1) | ||
| expect(createCountB).toBe(1) | ||
| expect(createdA.size).toBe(1) | ||
| expect(createdB.size).toBe(1) | ||
| expect(editorA?.isDestroyed).toBe(false) | ||
| expect(editorB?.isDestroyed).toBe(false) | ||
| expect(editorA).not.toBe(editorB) | ||
|
|
||
| unmount() | ||
| }) | ||
|
|
||
| it('does not throw and still creates exactly one editor when immediatelyRender is false under StrictMode', async () => { | ||
| let createCount = 0 | ||
|
|
||
| function TestComponent() { | ||
| useEditor({ | ||
| immediatelyRender: false, | ||
| extensions: [Document, Text, Paragraph], | ||
| onCreate: () => { | ||
| createCount += 1 | ||
| }, | ||
| }) | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| let unmount: () => void = () => {} | ||
|
|
||
| expect(() => { | ||
| ;({ unmount } = render( | ||
| React.createElement(React.StrictMode, null, React.createElement(TestComponent)), | ||
| )) | ||
| }).not.toThrow() | ||
|
|
||
| await flushTimers(100) | ||
|
|
||
| expect(createCount).toBe(1) | ||
|
|
||
| unmount() | ||
| }) | ||
|
|
||
| it('handles a full unmount and remount cycle correctly under StrictMode', async () => { | ||
| // Tracks *deltas* around the real show/hide toggle, rather than an | ||
| // absolute destroyCount, so this stays correct regardless of exactly | ||
| // when the guard's ref is (re-)initialized across mounts. | ||
| let createCount = 0 | ||
| let destroyCount = 0 | ||
|
|
||
| function TestComponent() { | ||
| useEditor({ | ||
| extensions: [Document, Text, Paragraph], | ||
| onCreate: () => { | ||
| createCount += 1 | ||
| }, | ||
| onDestroy: () => { | ||
| destroyCount += 1 | ||
| }, | ||
| }) | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| function Wrapper({ show }: { show: boolean }) { | ||
| return show ? React.createElement(TestComponent) : null | ||
| } | ||
|
|
||
| const { rerender, unmount } = render( | ||
| React.createElement(React.StrictMode, null, React.createElement(Wrapper, { show: true })), | ||
| ) | ||
|
|
||
| await flushTimers(100) | ||
| expect(createCount).toBe(1) | ||
|
|
||
| const destroyCountBeforeHiding = destroyCount | ||
|
|
||
| rerender( | ||
| React.createElement(React.StrictMode, null, React.createElement(Wrapper, { show: false })), | ||
| ) | ||
| await flushTimers(100) | ||
| expect(destroyCount - destroyCountBeforeHiding).toBe(1) | ||
|
|
||
| rerender( | ||
| React.createElement(React.StrictMode, null, React.createElement(Wrapper, { show: true })), | ||
| ) | ||
| await flushTimers(100) | ||
| expect(createCount).toBe(2) | ||
|
|
||
| unmount() | ||
| }) | ||
|
|
||
| it('does not crash the render if a user-provided onCreate throws', async () => { | ||
| function TestComponent() { | ||
| useEditor({ | ||
| extensions: [Document, Text, Paragraph], | ||
| onCreate: () => { | ||
| throw new Error('boom from onCreate') | ||
| }, | ||
| }) | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| const caughtAsync: unknown[] = [] | ||
| const onUnhandled = (error: unknown) => { | ||
| caughtAsync.push(error) | ||
| } | ||
|
|
||
| process.on('uncaughtException', onUnhandled) | ||
|
|
||
| let unmount: () => void = () => {} | ||
|
|
||
| try { | ||
| expect(() => { | ||
| ;({ unmount } = render( | ||
| React.createElement(React.StrictMode, null, React.createElement(TestComponent)), | ||
| )) | ||
| }).not.toThrow() | ||
|
|
||
| await flushTimers(500) | ||
| } finally { | ||
| unmount() | ||
| await flushTimers(100) | ||
| process.off('uncaughtException', onUnhandled) | ||
| } | ||
|
|
||
| // A throwing onCreate should surface asynchronously exactly once (same | ||
| // as it would have before this fix, since it fires from a 0ms timer or | ||
| // a React effect, never synchronously inside the render call itself) - | ||
| // not crash the render. | ||
| expect(caughtAsync.length).toBe(1) | ||
| expect(caughtAsync[0]).toBeInstanceOf(Error) | ||
| expect((caughtAsync[0] as Error).message).toBe('boom from onCreate') | ||
| }) | ||
|
|
||
| it('fires onCreate exactly once per deps change under StrictMode, including the first mount', async () => { | ||
| let createCount = 0 | ||
|
|
||
| function TestComponent({ depKey }: { depKey: string }) { | ||
| useEditor( | ||
| { | ||
| extensions: [Document, Text, Paragraph], | ||
| onCreate: () => { | ||
| createCount += 1 | ||
| }, | ||
| }, | ||
| [depKey], | ||
| ) | ||
|
|
||
| return null | ||
| } | ||
|
|
||
| const { rerender, unmount } = render( | ||
| React.createElement( | ||
| React.StrictMode, | ||
| null, | ||
| React.createElement(TestComponent, { depKey: 'a' }), | ||
| ), | ||
| ) | ||
|
|
||
| await flushTimers(200) | ||
| expect(createCount).toBe(1) | ||
|
|
||
| rerender( | ||
| React.createElement( | ||
| React.StrictMode, | ||
| null, | ||
| React.createElement(TestComponent, { depKey: 'b' }), | ||
| ), | ||
| ) | ||
| await flushTimers(200) | ||
| expect(createCount).toBe(2) | ||
|
|
||
| rerender( | ||
| React.createElement( | ||
| React.StrictMode, | ||
| null, | ||
| React.createElement(TestComponent, { depKey: 'c' }), | ||
| ), | ||
| ) | ||
| await flushTimers(200) | ||
| expect(createCount).toBe(3) | ||
|
|
||
| unmount() | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Guard against flushing
onCreatefor a destroyed editor.If
scheduleDestroy's 1ms timeout fires beforeonRenderruns (unlikely but possible when the event loop is congested), the editor is destroyed whilependingOnCreateEventstill holds a stale reference. The subsequentonRenderwould then callonCreatewith a destroyed editor, which is confusing for users.Adding a destroyed check is a one-line defensive guard:
🛡️ Proposed fix
if (this.pendingOnCreateEvent) { const event = this.pendingOnCreateEvent this.pendingOnCreateEvent = null - this.options.current.onCreate?.(event) + if (!event.editor.isDestroyed) { + this.options.current.onCreate?.(event) + } }📝 Committable suggestion
🤖 Prompt for AI Agents