startBatch

Start a manual notification batch to be closed with endBatch.

startBatchObservation and Batch

Start a manual notification batch to be closed with endBatch.

Overview

The startBatch function is used in conjunction with the batch function to batch multiple updates to refs, optimizing performance by reducing the number of observer notifications and triggers during a series of updates. The startBatch function initializes a batch operation, and any ref updates made after calling startBatch are batched together until the endBatch function is called.

Try it live

Same writes, different notification countsLive API
0Source value
0Observer callbacks

Choose an update strategy.

Each action adds three. Compare notification counts for the same amount of state change.

import { batch, endBatch, html, observe, ref, startBatch } from 'regor'

export function createBatching(interactive = false) {
  const source = ref(0),
    notifications = ref(0),
    value = ref(0)
  const mode = ref('Choose an update strategy.')
  observe(source, () => notifications(notifications() + 1))
  const update = (strategy: string) => {
    notifications(0)
    const writes = () => {
      for (let i = 0; i < 3; i++) source(source() + 1)
    }
    if (strategy === 'batch') batch(writes)
    else if (strategy === 'manual') {
      startBatch()
      try {
        writes()
      } finally {
        endBatch()
      }
    } else writes()
    value(source())
    mode(
      strategy === 'plain'
        ? 'Three separate writes'
        : strategy === 'batch'
          ? 'One batch callback'
          : 'startBatch + finally endBatch',
    )
  }
  return {
    interactive,
    notifications,
    value,
    mode,
    plain: () => update('plain'),
    grouped: () => update('batch'),
    manual: () => update('manual'),
  }
}

export const batchingTemplate = html` <div class="guide-demo">
  <div class="guide-session-bar">
    <button type="button" @click="plain" :disabled="!interactive">
      Three plain writes</button
    ><button type="button" @click="grouped" :disabled="!interactive">
      Use batch</button
    ><button type="button" @click="manual" :disabled="!interactive">
      Start / end batch
    </button>
  </div>
  <div class="guide-metrics api-metrics-pair">
    <div><output>{{ value }}</output><span>Source value</span></div>
    <div>
      <output>{{ notifications }}</output><span>Observer callbacks</span>
    </div>
  </div>
  <p class="guide-event" role="status">{{ mode }}</p>
  <p class="guide-hint">
    Each action adds three. Compare notification counts for the same amount of
    state change.
  </p>
</div>`
import { createApp, RegorConfig, useScope } from 'regor'
import { apiExamples } from './examples'

const element = document.getElementById('api-demo')
const name = element?.dataset.example
if (element && name && Object.hasOwn(apiExamples, name)) {
  const example = apiExamples[name as keyof typeof apiExamples]
  const scope = useScope<object>(() => example.create(true))
  const config =
    'config' in scope.context && scope.context.config instanceof RegorConfig
      ? scope.context.config
      : undefined
  createApp(scope, { element, template: example.template }, config)
}

Each action adds three to one ref. Compare plain writes, batch, and a manual start/end pair.

Usage

Starting a Batch

To start a batch of ref updates, call the startBatch function. Once a batch is started, any subsequent changes made to refs are considered part of that batch and are not immediately observed or triggered. Instead, observers are notified only once at the end of the batch.

import { batch, startBatch, endBatch, ref } from 'regor'

const myRef1 = ref(5)
const myRef2 = ref(10)

startBatch() // Start a batch

myRef1.value = 15
myRef2.value = 20

endBatch() // End the batch

// Observers are notified only once at the end of the batch
// Outputs:
// Observer triggered: 20
Always close a manual batch

Put endBatch in finally so an exception cannot leave later notifications inside an unfinished batch.

Notes

  • The startBatch function is used in conjunction with the endBatch function to group ref updates together within a batch. After starting a batch with startBatch, any subsequent changes to refs are included in that batch until the endBatch function is called.

  • Batching updates with the startBatch and endBatch functions can help improve the performance of your application when multiple changes are made to refs in a short period. It reduces the number of observer notifications and triggers, which can be especially beneficial in situations with complex reactivity logic.

  • It's essential to call the endBatch function to finalize the batch and notify observers of the ref updates made during the batch.

  • Important: When using the batch functions, keep in mind that reads of refs within the batch can return potentially stale or outdated values due to pausing auto-updates. Ensure that your code logic accounts for this situation when reading refs within a batch.

See Also

Related APIs and guides Continue with the references connected to startBatch.

Back to the API list