Skip to content

Commit

Permalink
Merge pull request #3776 from zalishchuk/use-sync-external-store-fix
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister authored Oct 25, 2022
2 parents 9d4b2dc + 9f7a922 commit c629fc2
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 3 deletions.
7 changes: 4 additions & 3 deletions compat/src/index.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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

0 comments on commit c629fc2

Please sign in to comment.