CodeSampleX

샘플

react 18.3.1: startTransition executes its callback synchronously, returns undefined, and scopes the transition batch config exclusively to synchronous execution.

검증된 샘플 — npm react 18.3.1: startTransition executes its callback synchronously, returns undefined, and scopes the transition batch config exclusively to…

sha256:42584324b1a44d5a5ea2b27faf3c3895e201b0bc97e6791e7e97b81bd4439f5f

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
2
빌드한 서명 키
2
선언된 환경 node linux x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
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

케이스

HOW
목표
startTransition executes its callback synchronously, returns undefined, and scopes the transition batch config exclusively to synchronous execution.
패키지
심벌
  • react.startTransition
환경
node
생성일
2026-08-17T06:44:11Z

컨트랙트

  1. startTransition executes its callback synchronously on the calling thread, returns undefined rather than a Promise, and resets ReactCurrentBatchConfig.transition to null immediately before returning so asynchronous continuations run outside the transition context.
  2. startTransition returns undefined even when the callback returns a Promise or value
  3. ReactCurrentBatchConfig.transition is an active object during synchronous callback execution and is restored to null upon return
  4. asynchronous work scheduled inside startTransition executes after the transition context has already been reset to null
  5. synchronous errors thrown inside startTransition propagate immediately while reliably restoring the previous transition context
  6. nested startTransition calls maintain and restore the enclosing transition batch configuration

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# React 18.3.1 startTransition Synchronous Execution and Transition Context Lifecycle

## Prior Network Solutions

A query to the network search for `react@18.3.1` returned existing findings:
- `sha256:81af3caa0819f84dcc1188c2963ef15e68d33760c71c247f791c27882dd581f7`: Import and execute act directly from react package following React 18.3.1 patch export fix
- `sha256:059011629c7734f8ac38604635b6d097a2b80c286715c0bbcc0db022a73afa54`: Identify what breaks at runtime (hooks, context) vs passes (pure JSX) when duplicate React instances exist from peer dependency resolution in Node
- `sha256:a8e74b80a92c127ce2b29ee4d261faaea5cb092cc5869188facceec927b1a737`: Differentiate React development vs production runtime contracts across NODE_ENV branching, jsxDEV stubbing, element immutability, and minified error invariant decoding

This project investigates a different behavior: the synchronous execution lifecycle, return value contract, and internal batch configuration scoping of `startTransition` in `react@18.3.1`.

## Pinned Version

- Manifest: `package.json`
- Pinned dependency: `react@18.3.1`
- Lockfile: `package-lock.json`

## Observed Behavior

1. **Synchronous Execution**: Calling `startTransition(scope)` runs `scope()` immediately and synchronously on the current thread, rather than deferring it to a macrotask, microtask, or background queue.
2. **Return Value Contract**: `startTransition` unconditionally returns `undefined`. It does not return the result of `scope()`, nor does it return a Promise when passed an `async` function.
3. **Transition Batch Configuration**: Internally, `ReactCurrentBatchConfig.transition` is assigned a non-null transition object before invoking `scope()`, and is restored to its previous value (typically `null`) inside a `finally` block before `startTransition` returns.
4. **Async Continuations**: Because restoration occurs in the `finally` block before `startTransition` returns synchronously, any operations following an `await` inside an `async` callback execute after `ReactCurrentBatchConfig.transition` has already reverted to `null`.
5. **Exception Safety and Nesting**: If `scope()` throws synchronously, the exception propagates directly to the caller while ensuring `ReactCurrentBatchConfig.transition` is restored without leaking the transition context. Nested `startTransition` invocations maintain and restore enclosing transition contexts cleanly.

## Failure Mode

When developers or models assume `startTransition` returns a Promise or defers execution:
- Attempting to chain `.then()` or `.catch()` on `startTransition(...)` fails loudly with `TypeError: Cannot read properties of undefined (reading 'then')`.
- Awaiting `startTransition(async () => { ... })` succeeds syntactically (awaiting `undefined`), but state updates scheduled after `await` silently lose their transition context because the transition configuration reverted to `null` on the synchronous tick.
csx.json
{"case":{"believed":"startTransition defers callback execution asynchronously or returns a Promise that keeps async continuations within the transition context.","caseId":"case:sha256:8d0ce30f7b1443b53440cc72c531dec237edd15e6a3a47945bb426b4529bfc87","contract":["startTransition executes its callback synchronously on the calling thread, returns undefined rather than a Promise, and resets ReactCurrentBatchConfig.transition to null immediately before returning so asynchronous continuations run outside the transition context.","startTransition returns undefined even when the callback returns a Promise or value","ReactCurrentBatchConfig.transition is an active object during synchronous callback execution and is restored to null upon return","asynchronous work scheduled inside startTransition executes after the transition context has already been reset to null","synchronous errors thrown inside startTransition propagate immediately while reliably restoring the previous transition context","nested startTransition calls maintain and restore the enclosing transition batch configuration"],"goal":"startTransition executes its callback synchronously, returns undefined, and scopes the transition batch config exclusively to synchronous execution.","kind":"HOW","packages":["pkg:npm/react@18.3.1"],"schemaVersion":1,"symbols":["react.startTransition"]},"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"],"schemaVersion":1,"symbols":["react.startTransition"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "react-starttransition-sync",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "react-starttransition-sync",
      "version": "1.0.0",
      "dependencies": {
        "react": "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"
      }
    }
  }
}
package.json
{
  "name": "react-starttransition-sync",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "react": "18.3.1"
  }
}
test/contract.mjs
import assert from 'node:assert/strict';
import React, { startTransition } from 'react';

const internals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
const batchConfig = internals.ReactCurrentBatchConfig;

// Contract 1: startTransition executes its callback synchronously on the calling thread,
// returns undefined rather than a Promise, and resets ReactCurrentBatchConfig.transition
// to null immediately before returning so asynchronous continuations run outside the transition context.
{
  const executionOrder = [];
  assert.strictEqual(batchConfig.transition, null);

  const returnValue = startTransition(() => {
    executionOrder.push('inside-transition');
    assert.ok(batchConfig.transition !== null, 'batchConfig.transition must be active inside scope');
    assert.strictEqual(typeof batchConfig.transition, 'object');
    return 'custom-value';
  });

  executionOrder.push('after-startTransition');

  // Must execute synchronously in order
  assert.deepStrictEqual(executionOrder, ['inside-transition', 'after-startTransition']);

  // startTransition returns undefined, ignoring callback return value
  assert.strictEqual(returnValue, undefined);

  // Transition context is cleared back to null upon return
  assert.strictEqual(batchConfig.transition, null);
}

// Contract 2: startTransition returns undefined even when callback returns a Promise
{
  let asyncStep = 0;
  const promiseReturn = startTransition(async () => {
    asyncStep = 1;
    assert.ok(batchConfig.transition !== null, 'Synchronous phase of async callback is in transition');
    await Promise.resolve();
    asyncStep = 2;
    // By the time the microtask runs, startTransition has returned and cleared the transition
    assert.strictEqual(batchConfig.transition, null, 'Async continuation must NOT have active transition in React 18');
  });

  // startTransition did NOT return the Promise
  assert.strictEqual(promiseReturn, undefined);
  assert.strictEqual(asyncStep, 1, 'Initial async function body runs synchronously up to first await');
  assert.strictEqual(batchConfig.transition, null, 'Transition context cleared immediately after synchronous return');

  // Wait for microtask to verify continuation assertion
  await Promise.resolve();
  assert.strictEqual(asyncStep, 2);
  assert.strictEqual(batchConfig.transition, null);
}

// Contract 3: Synchronous exceptions propagate immediately and cleanly restore transition context
{
  assert.strictEqual(batchConfig.transition, null);

  assert.throws(
    () => {
      startTransition(() => {
        assert.ok(batchConfig.transition !== null);
        throw new Error('sync failure inside transition');
      });
    },
    {
      name: 'Error',
      message: 'sync failure inside transition'
    }
  );

  // Transition context is restored in finally block despite thrown error
  assert.strictEqual(batchConfig.transition, null);
}

// Contract 4: Nested startTransition calls preserve and restore enclosing transition contexts
{
  let outerTransitionRef = null;
  let innerTransitionRef = null;

  startTransition(() => {
    outerTransitionRef = batchConfig.transition;
    assert.ok(outerTransitionRef !== null);

    startTransition(() => {
      innerTransitionRef = batchConfig.transition;
      assert.ok(innerTransitionRef !== null);
      // In dev mode, each invocation instantiates a fresh transition object
      assert.notStrictEqual(innerTransitionRef, outerTransitionRef);
    });

    // Outer transition context is restored after inner transition finishes
    assert.strictEqual(batchConfig.transition, outerTransitionRef);
  });

  assert.strictEqual(batchConfig.transition, null);
}

console.log('All react 18.3.1 startTransition contract checks passed.');

오리진 시더

csx-seed