CodeSampleX

Exemplo

react 18.3.1: Prove React 18.3.1 useId generates colon-delimited opaque tree identifiers, ignores any passed prefix arguments, and throws outside component render.

Amostra verificada para npm react 18.3.1: Prove React 18.3.1 useId generates colon-delimited opaque tree identifiers, ignores any passed prefix arguments…

sha256:eda56e7cf91cd1f75dc6f5921668c23a13d91aa663e61aac06c781b55fdef6d5

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
2
Chaves de assinatura que o compilaram
2
Ambiente declarado node linux x64 node node npm

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18

Caso

HOW
Objetivo
Prove React 18.3.1 useId generates colon-delimited opaque tree identifiers, ignores any passed prefix arguments, and throws outside component render.
Pacotes
Símbolos
  • useId
Ambiente
node
Criado
2026-08-18T10:59:19Z

Contrato

  1. useId returns colon-delimited strings like :R0: that ignore any prefix arguments passed to the hook and cannot be used directly in unescaped CSS ID selectors.
  2. Calling useId outside of a React component render throws a TypeError due to the missing dispatcher.
  3. Calling useId multiple times in the same component produces hierarchical colon-wrapped slot identifiers such as :R0: and :R0H1:.
  4. Multiple related element identifiers are derived by appending suffixes to a single useId root string.

Arquivos

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# React 18.3.1 `useId` Hook Behavior

## Prior Knowledge Search
The knowledge cache returned an existing sample (`sha256:2eb43c5745dcb728ff021939948fab7b4a3a4a8d033e8cb7385ded4f6ef4e1e7`) that verified `startTransition` execution semantics and `renderToString` with `identifierPrefix` across multiple roots. This sample investigates different, unverified behaviors and common traps of `useId` itself.

## Pinned Release
- `react`: `18.3.1`
- `react-dom`: `18.3.1`

## Observed Behavior and Traps

### 1. Argument Ignoring Trap
`useId` takes 0 arguments. When developers or tools pass a prefix string or configuration object (e.g., `useId('form-prefix')` or `useId({ prefix: 'user' })`), React silently ignores all arguments and generates the positional slot identifier (e.g., `:R0:`). If code relies on `useId` to inject a custom prefix, this fails silently with IDs that do not contain the requested prefix string.

### 2. Colon Delimiters and CSS Selector Syntax
`useId` produces strings enclosed by colons (e.g., `:R0:`, `:R0H1:` during server-side rendering). While valid in HTML `id` attributes, colons designate pseudo-classes in CSS selector syntax. Consequently, unescaped queries like `document.querySelector('#' + id)` fail loudly with a DOMException / CSS syntax error. Access requires `document.getElementById(id)` or `CSS.escape(id)`.

### 3. Invocation Outside Component Lifecycle
Calling `useId()` outside the render lifecycle of a React function component (e.g., during module initialization or standalone functions) throws a `TypeError` (`Cannot read properties of null (reading 'useId')`) because no hook dispatcher is mounted.

### 4. Multiple Hooks and Suffix Derivation
Multiple `useId()` invocations within the same component produce hierarchical slot IDs (`:R0:`, `:R0H1:`, `:R0H2:`). To associate multiple DOM nodes (such as an `<input>` and its `aria-describedby` hint), React recommends calling `useId` once per component and appending descriptive suffixes (e.g., `${id}-name`, `${id}-hint`).
csx.json
{"case":{"believed":"React useId accepts a prefix string parameter to customize generated element IDs and produces unescaped CSS-compatible selector strings.","caseId":"case:sha256:b9b9fa5173791dcb5e2f7ff60baf244021a2268b98fcfb3c251221b87ffefa85","contract":["useId returns colon-delimited strings like :R0: that ignore any prefix arguments passed to the hook and cannot be used directly in unescaped CSS ID selectors.","Calling useId outside of a React component render throws a TypeError due to the missing dispatcher.","Calling useId multiple times in the same component produces hierarchical colon-wrapped slot identifiers such as :R0: and :R0H1:.","Multiple related element identifiers are derived by appending suffixes to a single useId root string."],"goal":"Prove React 18.3.1 useId generates colon-delimited opaque tree identifiers, ignores any passed prefix arguments, and throws outside component render.","kind":"HOW","packages":["pkg:npm/react@18.3.1","pkg:npm/react-dom@18.3.1"],"schemaVersion":1,"symbols":["useId"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/react@18.3.1","pkg:npm/react-dom@18.3.1"],"schemaVersion":1,"symbols":["useId"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "react-useid-contract",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "react-useid-contract",
      "version": "1.0.0",
      "dependencies": {
        "react": "18.3.1",
        "react-dom": "18.3.1"
      }
    },
    "node_modules/js-tokens": {
      "version": "4.0.0",
      "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
      "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
      "license": "MIT"
    },
    "node_modules/loose-envify": {
      "version": "1.4.0",
      "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
      "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
      "license": "MIT",
      "dependencies": {
        "js-tokens": "^3.0.0 || ^4.0.0"
      },
      "bin": {
        "loose-envify": "cli.js"
      }
    },
    "node_modules/react": {
      "version": "18.3.1",
      "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
      "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0"
      },
      "engines": {
        "node": ">=0.10.0"
      }
    },
    "node_modules/react-dom": {
      "version": "18.3.1",
      "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
      "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0",
        "scheduler": "^0.23.2"
      },
      "peerDependencies": {
        "react": "^18.3.1"
      }
    },
    "node_modules/scheduler": {
      "version": "0.23.2",
      "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
      "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
      "license": "MIT",
      "dependencies": {
        "loose-envify": "^1.1.0"
      }
    }
  }
}
package.json
{
  "name": "react-useid-contract",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "react": "18.3.1",
    "react-dom": "18.3.1"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import React, { useId, createElement } from 'react';
import { renderToString } from 'react-dom/server';

// 1. Calling useId outside component render throws a TypeError
assert.throws(
  () => {
    useId();
  },
  {
    name: 'TypeError',
    message: /Cannot read properties of null \(reading 'useId'\)|Cannot read property 'useId' of null/,
  }
);

// 2. Passing arguments to useId is ignored; it returns colon-wrapped tree IDs
let capturedId1, capturedId2;
function PrefixTestComponent() {
  capturedId1 = useId('custom-prefix');
  capturedId2 = useId({ prefix: 'user-input' });
  return createElement('div', { id: capturedId1 },
    createElement('span', { id: capturedId2 })
  );
}

const renderedPrefixHtml = renderToString(createElement(PrefixTestComponent));

// IDs are colon-delimited and ignore the passed arguments completely
assert.strictEqual(capturedId1, ':R0:');
assert.strictEqual(capturedId2, ':R0H1:');
assert.strictEqual(capturedId1.startsWith(':') && capturedId1.endsWith(':'), true);
assert.strictEqual(capturedId2.startsWith(':') && capturedId2.endsWith(':'), true);
assert.strictEqual(capturedId1.includes('custom-prefix'), false);
assert.strictEqual(capturedId2.includes('user-input'), false);
assert.strictEqual(
  renderedPrefixHtml,
  '<div id=":R0:"><span id=":R0H1:"></span></div>'
);

// 3. Multi-hook slot hierarchy within the same component
let multiId0, multiId1, multiId2;
function MultiHookComponent() {
  multiId0 = useId();
  multiId1 = useId();
  multiId2 = useId();
  return createElement('div', null, multiId0, multiId1, multiId2);
}

renderToString(createElement(MultiHookComponent));
assert.strictEqual(multiId0, ':R0:');
assert.strictEqual(multiId1, ':R0H1:');
assert.strictEqual(multiId2, ':R0H2:');

// 4. Deriving related IDs by suffixing a single useId root
let formId, nameInputId, nameHintId;
function AccessibleForm() {
  formId = useId();
  nameInputId = `${formId}-name`;
  nameHintId = `${formId}-name-hint`;
  return createElement('form', { id: formId },
    createElement('input', { id: nameInputId, 'aria-describedby': nameHintId }),
    createElement('span', { id: nameHintId }, 'Enter your full name')
  );
}

const formHtml = renderToString(createElement(AccessibleForm));
assert.strictEqual(nameInputId, ':R0:-name');
assert.strictEqual(nameHintId, ':R0:-name-hint');
assert.strictEqual(
  formHtml,
  '<form id=":R0:"><input id=":R0:-name" aria-describedby=":R0:-name-hint"/><span id=":R0:-name-hint">Enter your full name</span></form>'
);

Seeder de origem

csx-seed