Skip to content

Commit 978c0b9

Browse files
authored
Implement flushSync (#5036)
1 parent af4c459 commit 978c0b9

File tree

2 files changed

+15
-13
lines changed

2 files changed

+15
-13
lines changed

compat/src/index.js

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@ import {
55
createRef,
66
Component,
77
createContext,
8-
Fragment
8+
Fragment,
9+
options
910
} from 'preact';
1011
import {
1112
useState,
@@ -131,15 +132,20 @@ function findDOMNode(component) {
131132
const unstable_batchedUpdates = (callback, arg) => callback(arg);
132133

133134
/**
134-
* In React, `flushSync` flushes the entire tree and forces a rerender. It's
135-
* implmented here as a no-op.
135+
* In React, `flushSync` flushes the entire tree and forces a rerender.
136136
* @template Arg
137137
* @template Result
138138
* @param {(arg: Arg) => Result} callback function that runs before the flush
139139
* @param {Arg} [arg] Optional argument that can be passed to the callback
140140
* @returns
141141
*/
142-
const flushSync = (callback, arg) => callback(arg);
142+
const flushSync = (callback, arg) => {
143+
const prevDebounce = options.debounceRendering;
144+
options.debounceRendering = cb => cb();
145+
const res = callback(arg);
146+
options.debounceRendering = prevDebounce;
147+
return res;
148+
};
143149

144150
// compat to react-is
145151
export const isElement = isValidElement;

compat/test/browser/useSyncExternalStore.test.js

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

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

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

0 commit comments

Comments
 (0)