Skip to content

Commit c6f7ebb

Browse files
committed
Implement flushSync (#5036)
(cherry picked from commit 978c0b9)
1 parent 85eb98f commit c6f7ebb

File tree

2 files changed

+14
-12
lines changed

2 files changed

+14
-12
lines changed

compat/src/index.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
createContext,
55
createElement,
66
createRef,
7+
options,
78
cloneElement as preactCloneElement,
89
render as preactRender
910
} from 'preact';
@@ -121,15 +122,20 @@ function findDOMNode(component) {
121122
}
122123

123124
/**
124-
* In React, `flushSync` flushes the entire tree and forces a rerender. It's
125-
* implmented here as a no-op.
125+
* In React, `flushSync` flushes the entire tree and forces a rerender.
126126
* @template Arg
127127
* @template Result
128128
* @param {(arg: Arg) => Result} callback function that runs before the flush
129129
* @param {Arg} [arg] Optional argument that can be passed to the callback
130130
* @returns
131131
*/
132-
const flushSync = (callback, arg) => callback(arg);
132+
const flushSync = (callback, arg) => {
133+
const prevDebounce = options.debounceRendering;
134+
options.debounceRendering = cb => cb();
135+
const res = callback(arg);
136+
options.debounceRendering = prevDebounce;
137+
return res;
138+
};
133139

134140
/**
135141
* In React, `unstable_batchedUpdates` is a legacy feature that was made a no-op

compat/test/browser/useSyncExternalStore.test.jsx

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -380,11 +380,9 @@ describe('useSyncExternalStore', () => {
380380

381381
// Switch stores and update in the same batch
382382
await act(() => {
383-
ReactDOM.flushSync(() => {
384-
// This update will be disregarded
385-
storeA.set(2);
386-
setStore(storeB);
387-
});
383+
// This update will be disregarded
384+
storeA.set(2);
385+
setStore(storeB);
388386
});
389387
// Now reading from B instead of A
390388
assertLog([0]);
@@ -687,10 +685,8 @@ describe('useSyncExternalStore', () => {
687685

688686
// Update the store and getSnapshot at the same time
689687
await act(() => {
690-
ReactDOM.flushSync(() => {
691-
setGetSnapshot(() => getSnapshotB);
692-
store.set({ a: 1, b: 2 });
693-
});
688+
setGetSnapshot(() => getSnapshotB);
689+
store.set({ a: 1, b: 2 });
694690
});
695691
// It should read from B instead of A
696692
assertLog([2]);

0 commit comments

Comments
 (0)