Skip to content

Sponsor

Sponsor

Utilities and API Reference

A complete reference of everything available in the Reactive State module.


Global exports

The module creates two global objects and one global function:

GlobalWhat it contains
ReactiveStatecreate, form, async, collection
ReactiveUtilsFull API (state, effect, ref, store, component, etc.)
updateAllGlobal shortcut for ReactiveUtils.updateAll()

ReactiveUtils — Full API

State creation

MethodSyntaxReturns
state(obj)state({ count: 0 })Reactive proxy
createState(obj, bindings?)ReactiveUtils.createState({ count: 0 }, { '#el': 'count' })Reactive proxy with bindings
ref(value)ref(0)Reactive { value } wrapper
refs(defs)refs({ a: 0, b: '' })Object of refs
collection(items?)collection([])Reactive list with CRUD methods
list(items?)Alias for collection()Same as collection()
form(values?)form({ email: '' })Form state with validation
async(initial?)asyncState(null)Async state with loading/error
store(state, options?)store({}, { getters, actions })State with getters + actions
component(config)component({ state, computed, ... })Full component
reactive(state)reactive({ count: 0 })Chainable builder
builder(state)Alias for reactive()Same as reactive()

Reactivity primitives

MethodSyntaxReturns
effect(fn)effect(() => { ... })Cleanup function
effects(defs)effects({ a: fn1, b: fn2 })Combined cleanup function
computed(state, defs)computed(app, { doubled: fn })The state
watch(state, defs)watch(app, { count: callback })Combined cleanup function
bindings(defs)ReactiveUtils.bindings({ '#el': fn })Cleanup function

Utilities

MethodSyntaxDescription
batch(fn)batch(() => { ... })Group changes, effects run once
isReactive(obj)isReactive(app)Returns true if reactive
toRaw(obj)toRaw(app)Returns unwrapped object
notify(state, key?)notify(app, 'items')Manually trigger effects
pause()pause()Pause all effect execution
resume(flush?)resume(true)Resume effects, optionally flush
untrack(fn)untrack(() => app.count)Read without tracking
updateAll(state, updates)ReactiveUtils.updateAll(app, { ... })Mixed state + DOM update

ReactiveState — Simplified API

MethodMaps to
ReactiveState.create(obj)state(obj)
ReactiveState.form(values)form(values)
ReactiveState.async(initial)asyncState(initial)
ReactiveState.collection(items)collection(items)

Instance methods (on every reactive object)

These are available on every reactive state object. For most use cases, prefer the global shortcut functions below. Instance methods are documented in 05_instance-methods.md.

MethodSyntaxGlobal equivalent
computed(key, fn)app.computed('total', fn)computed(app, { total: fn })
watch(keyOrFn, callback)app.watch('count', cb)watch(app, 'count', cb)
batch(fn)app.batch(function() { ... })batch(() => { ... })
update(updates)app.update({ count: 5 })(instance-only)
set(updates)app.set({ count: c => c + 1 })(instance-only)
bind(defs)app.bind({ '#el': 'count' })(instance-only)
notify(key?)app.notify('items')notify(app, 'items')
rawapp.rawtoRaw(app)

DOMHelpers Integration

When DOMHelpers modules are loaded, the full ReactiveUtils API is added to each:

javascript
// All of these are equivalent:
state({ count: 0 });
Elements.state({ count: 0 });
Collections.state({ count: 0 });
Selector.state({ count: 0 });

Specialized bind methods

MethodSelector formatTargets
Elements.bind(defs)ID without #document.getElementById()
Collections.bind(defs)Class without .document.getElementsByClassName()
Selector.query.bind(defs)Any CSS selectordocument.querySelector()
Selector.queryAll.bind(defs)Any CSS selectordocument.querySelectorAll()

Iteration Utilities

The module also provides two standalone utility functions for iterating over objects.

eachEntries()

Iterates over an object's entries using Object.entries() and forEach().

javascript
eachEntries(obj, callback, selector?)
ParameterTypeDescription
objobjectThe object to iterate over
callbackfunction(key, value, index)Called for each entry
selectorstring (optional)CSS selector to render returned HTML

Returns: Accumulated HTML string if callback returns strings, otherwise undefined.

javascript
const users = { alice: 30, bob: 25, charlie: 35 };

// Simple iteration
eachEntries(users, (name, age, i) => {
  console.log(`${i}: ${name} is ${age}`);
});

// Generate HTML
const html = eachEntries(users, (name, age) => {
  return `<div>${name}: ${age}</div>`;
});
// html = "<div>alice: 30</div><div>bob: 25</div><div>charlie: 35</div>"

// Generate and render to DOM
eachEntries(users, (name, age) => {
  return `<li>${name} (${age})</li>`;
}, '#userList');
// Renders HTML into the element matching #userList

mapEntries()

Maps over an object's entries using Object.entries() and map().

javascript
mapEntries(obj, callback, joinHTMLOrSelector?, selector?)
ParameterTypeDescription
objobjectThe object to map over
callbackfunction(key, value, index)Transform function — should return a value
joinHTMLOrSelectorboolean or stringIf true, joins array as HTML. If string, treats as selector
selectorstring (optional)CSS selector when first param is boolean

Returns: Array of transformed values, or joined HTML string.

javascript
const prices = { apple: 1.5, banana: 0.75, cherry: 3.0 };

// Map to array
const labels = mapEntries(prices, (fruit, price) => {
  return `${fruit}: $${price}`;
});
// ['apple: $1.50', 'banana: $0.75', 'cherry: $3.00']

// Join as HTML string
const html = mapEntries(prices, (fruit, price) => {
  return `<option value="${fruit}">${fruit} - $${price}</option>`;
}, true);
// "<option value="apple">apple - $1.5</option><option..."

// Render directly to DOM
mapEntries(prices, (fruit, price) => {
  return `<li>${fruit}: $${price}</li>`;
}, '#priceList');
// Renders into #priceList

Quick-pick guide

"I need to..."

NeedUse
Make an object reactivestate(obj)
Wrap a single valueref(value)
Run code when state changeseffect(fn)
Calculate a derived valuecomputed(app, { key: fn })
React when a property changeswatch(app, 'key', callback)
Group multiple changesbatch(fn)
Update state + DOM togetherapp.update({ ... }) (instance-only)
Connect state to DOM elementsapp.bind({ ... }) (instance-only)
Manage a listcollection()
Handle form stateform(initialValues)
Manage async operationsasyncState(initial)
Build a store with actionsstore(state, { getters, actions })
Create a full componentcomponent(config)
Build incrementallyreactive(state).computed(...).build()
Get the raw objecttoRaw(app)
Check if reactiveisReactive(obj)
Manually trigger updatesnotify(app, 'key')
Read without trackinguntrack(() => app.count)
Persist to storageautoSave(app, 'key')
Iterate an objecteachEntries(obj, callback)
Map an objectmapEntries(obj, callback)

Load order

html
<!-- 1. DOMHelpers Core (optional, for integration) -->
<script type="module">
  import { load } from 'https://cdn.jsdelivr.net/npm/dom-helpers-js@2.10.0/dist/dom-helpers.loader.esm.min.js';
  await load('reactive');
</script>

<!-- 2. Reactive State -->
<script type="module">
  import { load } from 'https://cdn.jsdelivr.net/npm/dom-helpers-js@2.10.0/dist/dom-helpers.loader.esm.min.js';
  await load('reactive');
</script>

The reactive module detects Elements, Collections, and Selector at load time and adds the API to each if they exist. Loading without DOMHelpers Core is fine — you'll use ReactiveUtils and ReactiveState directly.


Key takeaways

  1. Two global objects: ReactiveUtils (full API) and ReactiveState (simplified)
  2. One global function: updateAll() for mixed state + DOM updates
  3. Instance methods (computed, watch, batch, etc.) are on every reactive object
  4. DOMHelpers integration adds the full API to Elements, Collections, and Selector
  5. Specialized bind methods on each DOMHelpers module (ID, class, CSS selector)
  6. Iteration utilities (eachEntries, mapEntries) for object iteration with optional DOM rendering
  7. Start simple with state() + effect() — add complexity only as needed

Congratulations!

You've completed the Reactive State learning path. You now understand:

  • ✅ What reactive state is and why it exists
  • ✅ The Proxy system and dependency tracking
  • ✅ Effects, computed properties, and watchers
  • ✅ Instance methods for advanced state control
  • ✅ Specialized factories (ref, collection, form, async)
  • ✅ Architecture tools (store, component, builder)
  • ✅ Bindings and DOM integration
  • ✅ Real-world examples and patterns
  • ✅ The complete API reference

You're ready to build reactive UIs with DOMHelpers!