Skip to content

Commit

Permalink
backport #3776
Browse files Browse the repository at this point in the history
  • Loading branch information
JoviDeCroock committed Oct 26, 2022
1 parent f892739 commit a62e947
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
16 changes: 13 additions & 3 deletions compat/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,16 @@ export function useTransition() {
// styles/... before it attaches
export const useInsertionEffect = useLayoutEffect;

/**
* Check if two values are the same value
* @param {*} x
* @param {*} y
* @returns {boolean}
*/
function is(x, y) {
return (x === y && (x !== 0 || 1 / x === 1 / y)) || (x !== x && y !== y);
}

/**
* This is taken from https://github.com/facebook/react/blob/main/packages/use-sync-external-store/src/useSyncExternalStoreShimClient.js#L84
* on a high level this cuts out the warnings, ... and attempts a smaller implementation
Expand All @@ -152,18 +162,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
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 a62e947

Please sign in to comment.