Skip to content

Commit

Permalink
Add useSyncExternalStore to react-debug-tools (#22240)
Browse files Browse the repository at this point in the history
Adds support for useSyncExternalStore to react-debug-tools, which in
turn adds support for React Devtools.

Test plan: I added a test to ReactHooksInspectionIntegration, based on
existing one for useMutableSource.
  • Loading branch information
acdlite authored Sep 7, 2021
1 parent 8e80592 commit cfd8193
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
14 changes: 13 additions & 1 deletion packages/react-debug-tools/src/ReactDebugHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,19 @@ function useSyncExternalStore<T>(
subscribe: (() => void) => () => void,
getSnapshot: () => T,
): T {
throw new Error('Not yet implemented');
// useSyncExternalStore() composes multiple hooks internally.
// Advance the current hook index the same number of times
// so that subsequent hooks have the right memoized state.
nextHook(); // SyncExternalStore
nextHook(); // LayoutEffect
nextHook(); // Effect
const value = getSnapshot();
hookLog.push({
primitive: 'SyncExternalStore',
stackError: new Error(),
value,
});
return value;
}

function useTransition(): [boolean, (() => void) => void] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -878,4 +878,37 @@ describe('ReactHooksInspectionIntegration', () => {
},
]);
});

// @gate experimental || www
it('should support composite useSyncExternalStore hook', () => {
const useSyncExternalStore = React.unstable_useSyncExternalStore;
function Foo() {
const value = useSyncExternalStore(
() => () => {},
() => 'snapshot',
);
React.useMemo(() => 'memo', []);
return value;
}

const renderer = ReactTestRenderer.create(<Foo />);
const childFiber = renderer.root.findByType(Foo)._currentFiber();
const tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
expect(tree).toEqual([
{
id: 0,
isStateEditable: false,
name: 'SyncExternalStore',
value: 'snapshot',
subHooks: [],
},
{
id: 1,
isStateEditable: false,
name: 'Memo',
value: 'memo',
subHooks: [],
},
]);
});
});

0 comments on commit cfd8193

Please sign in to comment.