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

Use Object.is in useSyncExternalStore #3776

Merged
Merged
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
7 changes: 4 additions & 3 deletions compat/src/index.js
Expand Up @@ -27,6 +27,7 @@ import { Children } from './Children';
import { Suspense, lazy } from './suspense';
import { SuspenseList } from './suspense-list';
import { createPortal } from './portals';
import { is } from './util';
import {
hydrate,
render,
Expand Down Expand Up @@ -149,18 +150,18 @@ export function useSyncExternalStore(subscribe, getSnapshot) {
_instance._value = value;
_instance._getSnapshot = getSnapshot;

if (_instance._value !== getSnapshot()) {
if (!is(_instance._value, getSnapshot())) {
forceUpdate({ _instance });
}
}, [subscribe, value, getSnapshot]);

useEffect(() => {
if (_instance._value !== _instance._getSnapshot()) {
if (!is(_instance._value, _instance._getSnapshot())) {
forceUpdate({ _instance });
}

return subscribe(() => {
if (_instance._value !== _instance._getSnapshot()) {
if (!is(_instance._value, _instance._getSnapshot())) {
forceUpdate({ _instance });
}
});
Expand Down
10 changes: 10 additions & 0 deletions compat/src/util.js
Expand Up @@ -26,3 +26,13 @@ export function removeNode(node) {
let parentNode = node.parentNode;
if (parentNode) parentNode.removeChild(node);
}

/**
* Check if two values are the same value
* @param {*} x
* @param {*} y
* @returns {boolean}
*/
export function is(x, y) {
return (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y);
}
34 changes: 34 additions & 0 deletions compat/test/browser/hooks.test.js
Expand Up @@ -130,6 +130,40 @@ describe('React-18-hooks', () => {
expect(scratch.innerHTML).to.equal('<p>hello new world</p>');
});

it('getSnapshot can return NaN without causing infinite loop', () => {
let flush;
const subscribe = sinon.spy(cb => {
flush = cb;
return () => {};
});
let called = false;
const getSnapshot = sinon.spy(() => {
if (called) {
return NaN;
}

return 1;
});

const App = () => {
const value = useSyncExternalStore(subscribe, getSnapshot);
return <p>{value}</p>;
};

act(() => {
render(<App />, scratch);
});
expect(scratch.innerHTML).to.equal('<p>1</p>');
expect(subscribe).to.be.calledOnce;
expect(getSnapshot).to.be.calledThrice;

called = true;
flush();
rerender();

expect(scratch.innerHTML).to.equal('<p>NaN</p>');
});

it('should not call function values on subscription', () => {
let flush;
const subscribe = sinon.spy(cb => {
Expand Down