Skip to content
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

flush pending passive effects early on an interactive update #15644

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
40 changes: 40 additions & 0 deletions packages/react-dom/src/__tests__/ReactDOMHooks-test.js
Expand Up @@ -179,4 +179,44 @@ describe('ReactDOMHooks', () => {

expect(labelRef.current.innerHTML).toBe('abc');
});
it('should flush passive effects before interactive events', () => {
// related to #15057
// the test is a bit contrived since it'll never happen in a 'real' test/browser
// (the effect would flush on start and the clicks would never set state)
// but it does model setting state in an effect clean up that removes a previous handler

// users should probably wrap their code with unstable_interactiveUpdates? or
// use emitEffect?
const {useState, useEffect} = React;

function Foo() {
const [count, setCount] = useState(0);
const [enabled, setEnabled] = useState(true);
useEffect(() => {
return () => {
setEnabled(false);
};
});
function handleClick() {
setCount(x => x + 1);
}
return <button onClick={enabled ? handleClick : null}>{count}</button>;
}

ReactDOM.render(<Foo />, container);

container.firstChild.dispatchEvent(
new Event('click', {bubbles: true, cancelable: true}),
);
// Cleanup from first passive effect should remove the handler.
container.firstChild.dispatchEvent(
new Event('click', {bubbles: true, cancelable: true}),
);
container.firstChild.dispatchEvent(
new Event('click', {bubbles: true, cancelable: true}),
);

jest.runAllTimers();
expect(container.textContent).toBe('1');
});
});
3 changes: 2 additions & 1 deletion packages/react-reconciler/src/ReactFiberScheduler.js
Expand Up @@ -539,6 +539,7 @@ export function flushInteractiveUpdates() {
// an input event inside an effect, like with `element.click()`.
return;
}
flushPassiveEffects();
flushPendingDiscreteUpdates();
}

Expand Down Expand Up @@ -575,7 +576,7 @@ export function interactiveUpdates<A, B, C, R>(
if (workPhase === NotWorking) {
// TODO: Remove this call. Instead of doing this automatically, the caller
// should explicitly call flushInteractiveUpdates.
flushPendingDiscreteUpdates();
flushInteractiveUpdates();
}
return runWithPriority(UserBlockingPriority, fn.bind(null, a, b, c));
}
Expand Down