MCPcopy Create free account
hub / github.com/RobPruzan/react-scratch / useState

Function useState

src/react/core.ts:1613–1662  ·  view source on GitHub ↗
(initialValue: T)

Source from the content-addressed store, hash-verified

1611};
1612
1613export const useState = <T>(initialValue: T) => {
1614 if (!currentTreeRef.renderTree?.currentlyRendering) {
1615 throw new Error("Cannot call use state outside of a react component");
1616 }
1617
1618 const currentStateOrder =
1619 currentTreeRef.renderTree.currentLocalCurrentHookOrder;
1620 currentTreeRef.renderTree.currentLocalCurrentHookOrder += 1;
1621
1622 const capturedCurrentlyRenderingRenderNode =
1623 currentTreeRef.renderTree.currentlyRendering;
1624
1625 if (capturedCurrentlyRenderingRenderNode.kind === "empty-slot") {
1626 throw new Error(
1627 "Invariant Error: A node that triggered a set state cannot be an empty slot"
1628 );
1629 }
1630
1631 if (!capturedCurrentlyRenderingRenderNode.hasRendered) {
1632 capturedCurrentlyRenderingRenderNode.hooks.push({
1633 kind: "state",
1634 value: initialValue,
1635 });
1636 }
1637
1638 const hookMetadata =
1639 capturedCurrentlyRenderingRenderNode.hooks[currentStateOrder];
1640
1641 if (hookMetadata.kind !== "state") {
1642 throw new Error("Different number of hooks rendered between render");
1643 }
1644
1645 return [
1646 hookMetadata.value as T,
1647 (value: T) => {
1648 if (!capturedCurrentlyRenderingRenderNode.computedViewTreeNodeId) {
1649 throw new Error(
1650 "Invariant: set state trying to re-render unmounted component"
1651 );
1652 }
1653
1654 if (!currentTreeRef.viewTree || !currentTreeRef.renderTree) {
1655 throw new Error("Invariant error, no view tree or no render tree");
1656 }
1657
1658 hookMetadata.value = value;
1659 triggerReRender({ capturedCurrentlyRenderingRenderNode });
1660 },
1661 ] as const;
1662};
1663
1664export const render = (
1665 rootElement: ReturnType<typeof createElement>,

Callers

nothing calls this directly

Calls 1

triggerReRenderFunction · 0.85

Tested by

no test coverage detected