Skip to content

Commit

Permalink
useId (#22644)
Browse files Browse the repository at this point in the history
* Add useId to dispatcher

* Initial useId implementation

Ids are base 32 strings whose binary representation corresponds to the
position of a node in a tree.

Every time the tree forks into multiple children, we add additional bits
to the left of the sequence that represent the position of the child
within the current level of children.

    00101       00010001011010101
    ╰─┬─╯       ╰───────┬───────╯
  Fork 5 of 20       Parent id

The leading 0s are important. In the above example, you only need 3 bits
to represent slot 5. However, you need 5 bits to represent all the forks
at the current level, so we must account for the empty bits at the end.

For this same reason, slots are 1-indexed instead of 0-indexed.
Otherwise, the zeroth id at a level would be indistinguishable from
its parent.

If a node has only one child, and does not materialize an id (i.e. does
not contain a useId hook), then we don't need to allocate any space in
the sequence. It's treated as a transparent indirection. For example,
these two trees produce the same ids:

<>                          <>
  <Indirection>               <A />
    <A />                     <B />
  </Indirection>            </>
  <B />
</>

However, we cannot skip any materializes an id. Otherwise, a parent id
that does not fork would be indistinguishable from its child id. For
example, this tree does not fork, but the parent and child must have
different ids.

<Parent>
  <Child />
</Parent>

To handle this scenario, every time we materialize an id, we allocate a
new level with a single slot. You can think of this as a fork with only
one prong, or an array of children with length 1.

It's possible for the the size of the sequence to exceed 32 bits, the
max size for bitwise operations. When this happens, we make more room by
converting the right part of the id to a string and storing it in an
overflow variable. We use a base 32 string representation, because 32 is
the largest power of 2 that is supported by toString(). We want the base
to be large so that the resulting ids are compact, and we want the base
to be a power of 2 because every log2(base) bits corresponds to a single
character, i.e. every log2(32) = 5 bits. That means we can lop bits off
the end 5 at a time without affecting the final result.

* Incremental hydration

Stores the tree context on the dehydrated Suspense boundary's state
object so it resume where it left off.

* Add useId to react-debug-tools

* Add selective hydration test

Demonstrates that selective hydration works and ids are preserved even
after subsequent client updates.
  • Loading branch information
acdlite authored Nov 1, 2021
1 parent a0d991f commit ebf9ae8
Show file tree
Hide file tree
Showing 38 changed files with 1,819 additions and 77 deletions.
12 changes: 12 additions & 0 deletions packages/react-debug-tools/src/ReactDebugHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,17 @@ function useOpaqueIdentifier(): OpaqueIDType | void {
return value;
}

function useId(): string {
const hook = nextHook();
const id = hook !== null ? hook.memoizedState : '';
hookLog.push({
primitive: 'Id',
stackError: new Error(),
value: id,
});
return id;
}

const Dispatcher: DispatcherType = {
getCacheForType,
readContext,
Expand All @@ -361,6 +372,7 @@ const Dispatcher: DispatcherType = {
useSyncExternalStore,
useDeferredValue,
useOpaqueIdentifier,
useId,
};

// Inspect
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -628,7 +628,7 @@ describe('ReactHooksInspectionIntegration', () => {
it('should support composite useOpaqueIdentifier hook in concurrent mode', () => {
function Foo(props) {
const id = React.unstable_useOpaqueIdentifier();
const [state] = React.useState(() => 'hello', []);
const [state] = React.useState('hello');
return <div id={id}>{state}</div>;
}

Expand Down Expand Up @@ -656,6 +656,33 @@ describe('ReactHooksInspectionIntegration', () => {
});
});

it('should support useId hook', () => {
function Foo(props) {
const id = React.unstable_useId();
const [state] = React.useState('hello');
return <div id={id}>{state}</div>;
}

const renderer = ReactTestRenderer.create(<Foo />);
const childFiber = renderer.root.findByType(Foo)._currentFiber();
const tree = ReactDebugTools.inspectHooksOfFiber(childFiber);

expect(tree.length).toEqual(2);

expect(tree[0].id).toEqual(0);
expect(tree[0].isStateEditable).toEqual(false);
expect(tree[0].name).toEqual('Id');
expect(String(tree[0].value).startsWith('r:')).toBe(true);

expect(tree[1]).toEqual({
id: 1,
isStateEditable: true,
name: 'State',
value: 'hello',
subHooks: [],
});
});

describe('useDebugValue', () => {
it('should support inspectable values for multiple custom hooks', () => {
function useLabeledValue(label) {
Expand Down
Loading

0 comments on commit ebf9ae8

Please sign in to comment.