Skip to content

Commit

Permalink
Add useSyncExternalStore to react-debug-tools
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 committed Sep 7, 2021
1 parent c65b925 commit 62b3aee
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
15 changes: 14 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,20 @@ 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(); // State
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 62b3aee

Please sign in to comment.