Skip to content

Commit 9fd9496

Browse files
author
Sebastian Silbermann
committed
DevTools: Add support for useOptimistic Hook
1 parent 38ef167 commit 9fd9496

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

packages/react-debug-tools/src/ReactDebugHooks.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ function getPrimitiveStackCache(): Map<string, Array<any>> {
8080
// This type check is for Flow only.
8181
Dispatcher.useMemoCache(0);
8282
}
83+
Dispatcher.useOptimistic(0);
8384
} finally {
8485
readHookLog = hookLog;
8586
hookLog = [];
@@ -348,6 +349,25 @@ function useMemoCache(size: number): Array<any> {
348349
return data;
349350
}
350351

352+
function useOptimistic<S, A>(
353+
passthrough: S,
354+
reducer: ?(S, A) => S,
355+
): [S, (A) => void] {
356+
const hook = nextHook();
357+
let state;
358+
if (hook !== null) {
359+
state = hook.memoizedState;
360+
} else {
361+
state = passthrough;
362+
}
363+
hookLog.push({
364+
primitive: 'Optimistic',
365+
stackError: new Error(),
366+
value: state,
367+
});
368+
return [state, (action: A) => {}];
369+
}
370+
351371
const Dispatcher: DispatcherType = {
352372
use,
353373
readContext,
@@ -361,6 +381,7 @@ const Dispatcher: DispatcherType = {
361381
useInsertionEffect,
362382
useMemo,
363383
useMemoCache,
384+
useOptimistic,
364385
useReducer,
365386
useRef,
366387
useState,

packages/react-debug-tools/src/__tests__/ReactHooksInspectionIntegration-test.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,4 +1106,41 @@ describe('ReactHooksInspectionIntegration', () => {
11061106
},
11071107
]);
11081108
});
1109+
1110+
it('should support useOptimistic hook', () => {
1111+
const useOptimistic = React.useOptimistic;
1112+
function Foo() {
1113+
const [value] = useOptimistic('abc', currentState => currentState);
1114+
React.useMemo(() => 'memo', []);
1115+
React.useMemo(() => 'not used', []);
1116+
return value;
1117+
}
1118+
1119+
const renderer = ReactTestRenderer.create(<Foo />);
1120+
const childFiber = renderer.root.findByType(Foo)._currentFiber();
1121+
const tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
1122+
expect(tree).toEqual([
1123+
{
1124+
id: 0,
1125+
isStateEditable: false,
1126+
name: 'Optimistic',
1127+
value: 'abc',
1128+
subHooks: [],
1129+
},
1130+
{
1131+
id: 1,
1132+
isStateEditable: false,
1133+
name: 'Memo',
1134+
value: 'memo',
1135+
subHooks: [],
1136+
},
1137+
{
1138+
id: 2,
1139+
isStateEditable: false,
1140+
name: 'Memo',
1141+
value: 'not used',
1142+
subHooks: [],
1143+
},
1144+
]);
1145+
});
11091146
});

0 commit comments

Comments
 (0)