Skip to content

Commit

Permalink
Throw an error when calling root.render outside of a task (#49003)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: #49003

Changelog: [internal]

I was adding a benchmark for rendering thousands of views and it was surprisingly fast, until I realized I wasn't wrapping the call to `root.render` in `runTask`, which means the benchmark wasn't really doing the rendering, only scheduling a microtask that was never executed.

This is a safety mechanism to prevent those mistakes.

Reviewed By: sammy-SC

Differential Revision: D68771170

fbshipit-source-id: 5bd8e6ba9e1168db2320572c99b3a01ebd6aeeed
  • Loading branch information
rubennorte authored and facebook-github-bot committed Jan 28, 2025
1 parent 32fe244 commit c925872
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
16 changes: 16 additions & 0 deletions packages/react-native-fantom/src/__tests__/Fantom-itest.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,22 @@ describe('Fantom', () => {
},
);
});

it('throws when trying to render a root outside of a task', () => {
const root = Fantom.createRoot();

expect(() => {
root.render(<View />);
}).toThrow(
'Unexpected call to `render` outside of the event loop. Please call `render` within a `runTask` callback.',
);

expect(() => {
Fantom.runTask(() => {
root.render(<View />);
});
}).not.toThrow();
});
});

describe('getRenderedOutput', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/react-native-fantom/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,13 @@ class Root {
globalSurfaceIdCounter += 10;
}

render(element: MixedElement) {
render(element: MixedElement): void {
if (!flushingQueue) {
throw new Error(
'Unexpected call to `render` outside of the event loop. Please call `render` within a `runTask` callback.',
);
}

if (!this.#hasRendered) {
NativeFantom.startSurface(
this.#surfaceId,
Expand Down

0 comments on commit c925872

Please sign in to comment.