# Batching

Source: https://signy.dev/documentation/1/reactivity/batching/

When updates run, and how to group them.

## Updates run in a microtask

A signal write does not touch the DOM right away. Signy collects the changes and applies them in a microtask, so several writes in a row cause one update.

## batch()

`batch()` groups writes explicitly. Readers run once, after the function returns, and see the final values.

```js
batch(() => {
  this.firstName.value = 'Ada';
  this.lastName.value = 'Lovelace';
});
```

```js
const { Component, Signal, application, html, batch } = Signy;

class Swap extends Component {
  left = new Signal("🍎");
  right = new Signal("🍐");

  swap() {
    batch(() => {
      const left = this.left.value;
      this.left.value = this.right.value;
      this.right.value = left;
    });
  }

  render() {
    return html`
      <p>${() => this.left.value} and ${() => this.right.value}</p>
      <button onClick=${() => this.swap()}>Swap</button>
    `;
  }
}

application(Swap).mount("#batch-swap");
```

## flushAll()

`flushAll()` runs every pending notification, effect and DOM update right away. Use it in tests after a write. See [Testing](https://signy.dev/documentation/1/application/testing/index.html.md).

```js
count.value = 2;
flushAll();
expect(root.textContent).toBe('2');
```

`flushSync()` only delivers signal notifications. It does not run effects or DOM updates, so prefer `flushAll()`.
