CodeSampleX

Sample

react 18.3.1: Identify what breaks at runtime (hooks, context) vs passes (pure JSX) when duplicate React instances exist from peer dependency resolution in Node

Verified sample for npm react 18.3.1: Identify what breaks at runtime (hooks, context) vs passes (pure JSX) when duplicate React instances exist from peer…

sha256:059011629c7734f8ac38604635b6d097a2b80c286715c0bbcc0db022a73afa54

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
2
Declared environment node linux x64 node node npm

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-15
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

Case

HOW
Goal
Identify what breaks at runtime (hooks, context) vs passes (pure JSX) when duplicate React instances exist from peer dependency resolution in Node
Packages
Symbols
  • react.createElement
  • react.useState
  • react.createContext
  • react.isValidElement
  • react-dom/server.renderToString
Environment
node
Created
2026-08-15T17:13:19Z

Contract

  1. assert duplicate React modules share Symbol.for('react.element') enabling cross-instance element validation and stateless SSR
  2. assert duplicate React modules maintain isolated ReactSharedInternals causing hook dispatcher to be null during SSR and throwing TypeError on useState
  3. assert duplicate React createContext instances fail context propagation silently due to referential inequality across copies
  4. assert unifying peer dependency resolution to a shared module instance restores hook execution and context propagation

Files

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

Download the source artifact (tar.gz)

Source

NOTES.md
# React DOM Peer Dependency Resolution & Duplicate Copy Trap

## CSX Search Result
- `search_known_solution` answered: **MISS** (no relevant sample exists in CodeSampleX for React/ReactDOM peer dependency resolution and duplicate runtime state).

## What a Model Would Have Written
A model would have assumed that having multiple copies of `react` either always fails at install time via npm `ERESOLVE` or uniformly breaks all JSX/element creation at runtime due to module instance mismatch.

## How the Wrong Version Fails
The wrong version fails bimodally: pure stateless JSX elements pass silently with a green build because `$$typeof` uses the process-global `Symbol.for('react.element')`, Context propagation fails silently by ignoring Provider values and reverting to defaults (`Context1 !== Context2`), and hook-based components (`useState`) fail loudly at runtime with `TypeError: Cannot read properties of null (reading 'useState')` because `react-dom/server` only attaches its dispatcher to the root React instance.
csx.json
{"case":{"caseId":"case:sha256:165e69e53c1b16907f9840cf63ebb128f34b0b80f67c4ee9319734c14c0bbabf","constraints":{"runtime":"node"},"contract":["assert duplicate React modules share Symbol.for('react.element') enabling cross-instance element validation and stateless SSR","assert duplicate React modules maintain isolated ReactSharedInternals causing hook dispatcher to be null during SSR and throwing TypeError on useState","assert duplicate React createContext instances fail context propagation silently due to referential inequality across copies","assert unifying peer dependency resolution to a shared module instance restores hook execution and context propagation"],"goal":"Identify what breaks at runtime (hooks, context) vs passes (pure JSX) when duplicate React instances exist from peer dependency resolution in Node","kind":"HOW","packages":["pkg:npm/react@18.3.1","pkg:npm/react-dom@18.3.1"],"schemaVersion":1,"symbols":["react.createElement","react.useState","react.createContext","react.isValidElement","react-dom/server.renderToString"]},"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":["react.createElement","react.useState","react.createContext","react.isValidElement","react-dom/server.renderToString"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-react-peer-resolution",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-react-peer-resolution",
      "version": "1.0.0",
      "license": "ISC",
      "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": "npm-react-peer-resolution",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "react": "18.3.1",
    "react-dom": "18.3.1"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import path from 'node:path';

const require = createRequire(import.meta.url);

// Load primary React instance (as resolved by the host app / react-dom)
const ReactHost = require('react');
const ReactDOMServer = require('react-dom/server');

// Simulate a duplicate React instance (as produced by nested dependencies or duplicate packaging)
const hostReactKey = require.resolve('react');
const reactDir = path.dirname(hostReactKey);

for (const key of Object.keys(require.cache)) {
  if (key.startsWith(reactDir) && !key.includes('react-dom')) {
    delete require.cache[key];
  }
}
const ReactDuplicate = require('react');

// Contract Assertion 1: Distinct module identity & isolated internals
// Naive assumption: Node or React unifies identical versions into a single instance
assert.notEqual(ReactHost, ReactDuplicate, 'Duplicate import must create distinct module object');
assert.notEqual(
  ReactHost.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,
  ReactDuplicate.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,
  'Secret internals (dispatcher registry) must be isolated between duplicate copies'
);

// Contract Assertion 2: Pure JSX / createElement compatibility across duplicate instances
// Naive assumption: Elements created by a duplicate copy will fail validation or crash react-dom
function PureCard(props) {
  return ReactDuplicate.createElement('div', { className: 'card' }, props.title);
}

const pureElement = ReactDuplicate.createElement(PureCard, { title: 'Cross-Instance Element' });

// Global Symbol.for('react.element') ensures cross-instance element validity
assert.equal(ReactHost.isValidElement(pureElement), true);
assert.equal(ReactDuplicate.isValidElement(pureElement), true);

const renderedPure = ReactDOMServer.renderToString(
  ReactHost.createElement('section', null, pureElement)
);
assert.equal(
  renderedPure,
  '<section><div class="card">Cross-Instance Element</div></section>',
  'Stateless components from duplicate React copies must render successfully'
);

// Contract Assertion 3: Hooks break at runtime during SSR
// Naive assumption: react-dom/server will render useState from duplicate copy if versions match
function StatefulCard(props) {
  const [count] = ReactDuplicate.useState(42);
  return ReactDuplicate.createElement('span', null, `Count: ${count}`);
}

const statefulElement = ReactHost.createElement(StatefulCard);

// Suppress expected console.error from React's invalid hook call warning during this assertion
const origError = console.error;
let warningLogged = false;
console.error = (...args) => {
  if (typeof args[0] === 'string' && args[0].includes('Invalid hook call')) {
    warningLogged = true;
    return;
  }
  origError(...args);
};

let hookError = null;
try {
  ReactDOMServer.renderToString(statefulElement);
} catch (err) {
  hookError = err;
} finally {
  console.error = origError;
}

assert.ok(hookError, 'Rendering a hook component from a duplicate React copy must throw');
assert.equal(hookError.name, 'TypeError');
assert.ok(
  hookError.message.includes("Cannot read properties of null (reading 'useState')") ||
  hookError.message.includes("Cannot read property 'useState' of null"),
  `Unexpected error message: ${hookError.message}`
);
assert.equal(warningLogged, true, 'React must log the multi-copy invalid hook call warning');

// Contract Assertion 4: Context silently fails across duplicate instances
// Naive assumption: Context with identical default values and shapes connects across copies
const HostContext = ReactHost.createContext('default-theme');
const DuplicateContext = ReactDuplicate.createContext('default-theme');

function HostConsumer() {
  return ReactHost.createElement(HostContext.Consumer, null, val =>
    ReactHost.createElement('span', { id: 'host-val' }, val)
  );
}

function DuplicateConsumer() {
  return ReactDuplicate.createElement(DuplicateContext.Consumer, null, val =>
    ReactDuplicate.createElement('span', { id: 'dup-val' }, val)
  );
}

// Case A: Matching context provider + consumer -> propagates provided value
const matchedHtml = ReactDOMServer.renderToString(
  ReactHost.createElement(HostContext.Provider, { value: 'dark-theme' },
    ReactHost.createElement(HostConsumer)
  )
);
assert.equal(matchedHtml, '<span id="host-val">dark-theme</span>');

// Case B: Host provider wrapping Duplicate consumer -> SILENT fallback to default value
const mismatchedHtml = ReactDOMServer.renderToString(
  ReactHost.createElement(HostContext.Provider, { value: 'dark-theme' },
    ReactHost.createElement(DuplicateConsumer)
  )
);
// It does NOT throw, but silently fails to receive 'dark-theme'
assert.equal(
  mismatchedHtml,
  '<span id="dup-val">default-theme</span>',
  'Context across duplicate React instances must silently fall back to default value'
);

// Contract Assertion 5: Unified peer dependency resolution restores full functionality
// When resolved against the same module instance (standard peerDependencies behavior):
function UnifiedHookComponent() {
  const [val] = ReactHost.useState('unified-state');
  return ReactHost.createElement('b', null, val);
}
const unifiedHtml = ReactDOMServer.renderToString(
  ReactHost.createElement(UnifiedHookComponent)
);
assert.equal(unifiedHtml, '<b>unified-state</b>');

Origin Seeder

anonymous