Skip to main content

How it works

Expression evaluation

When an expression is evaluated, it's done so in the context of the state object. This means that any variables referenced in the expression are looked up in the state object.

Cog under the hood
const state = {
meaningOfLife: 41,
};
const expression = "meaningOfLife + 1";
evaluateExpression(expression, state); // 42

Cog calls the evaluateExpression function internally when rendering UI with reactive variables. It creates a new function with values from the state in it's scope and executes the expression.

Example function created by evaluateExpression
const func = () => {
const meaningOfLife = 41; // variable form the state

return meaningOfLife + 1; // expression
}();

Reconciliation

The reconcile function is responsible for determining the minimal, fine-grained updates to the DOM when the state changes. It iterates over all reactive nodes (elements that depend on the state). For each node, it checks if the node needs to be updated. This is done using a combination of signals and Virtual DOM diffing to efficiently update the DOM when the state changes.

  1. Signals: The nodeNeedsUpdate function checks if a node needs to be updated. This is done by checking if any of the state variables used in the node's expressions have changed. This is a form of signaling, where a change in state signals that a node may need to be updated.

  2. Virtual DOM diffing: If a node needs to be updated, the reconcile function first generates a new virtual DOM node by evaluating the node's template with the updated state. This new node is then compared with the old node to determine the changes. This is done by the compareNodes function, which returns a list of changed nodes. For each changed node, the handleNodeChanges function is called, which updates the original node in the DOM with the changes. This is a form of Virtual DOM diffing, where a new virtual DOM is compared with the old one to determine the minimal necessary updates to the real DOM.

By combining signals and Virtual DOM diffing, the reconcile function can efficiently update the DOM when the state changes, only updating the nodes that depend on the changed state variables and only applying the minimal necessary changes to these nodes.