App

The App function creates the main Cerebral controller instance that manages your application state and logic.

Initialization 

import App from 'cerebral'
import main from './main' // The root module

const app = App(main, {
  // Options (all optional)
  devtools: null, // Debugger integration
  throwToConsole: true, // Log errors to console
  noRethrow: false, // Prevent rethrow of errors after handling
  stateChanges: {}, // Initial state changes
  returnSequencePromise: false, // Make sequences return promises
  hotReloading: false // Handle hot reloading
})

Options 

OptionTypeDefaultDescription
devtoolsObject/nullnullDebugger configuration
throwToConsoleBooleantrueLog caught errors to console
noRethrowBooleanfalsePrevent rethrowing errors after handling them
stateChangesObject{}Initial state changes to apply
returnSequencePromiseBooleanfalseMake sequence executions return promises
hotReloadingBooleanfalseEnable smart merging for hot reloading

State Management 

getState 

Gets state from a specific path.

// Get value at path
const user = app.getState('user')

// Get nested value
const username = app.getState('user.details.name')

// Get full state tree
const fullState = app.getState()

get 

Gets a value using a tag.

import { state } from 'cerebral'

// Get state using tag
const user = app.get(state`user`)

// With dynamic path
const item = app.get(state`items.${itemId}`)

Sequences 

getSequence 

Returns a callable sequence from a specific path.

// Get a sequence
const authenticate = app.getSequence('auth.authenticate')

// Run the sequence with optional payload
authenticate({ username: 'user', password: 'pass' })

getSequences 

Returns all sequences from a module.

// Get all sequences from a module
const authSequences = app.getSequences('auth')

// Run a sequence from the collection
authSequences.authenticate({ username: 'user' })

runSequence 

Run an arbitrary sequence definition.

// Run an inline sequence
app.runSequence(
  'myInlineSequence',
  [setLoading(true), fetchData, setLoading(false)],
  { id: 123 }
)

// Run a predefined sequence by path
app.runSequence('auth.authenticate', {
  username: 'user',
  password: 'pass'
})

Module Management 

addModule 

Add a module after app initialization.

import analyticsModule from './modules/analytics'

// Add a module at a specific path
app.addModule('analytics', analyticsModule)

// Add a nested module
app.addModule('settings.theme', themeModule)

removeModule 

Remove a module from the app.

// Remove a module
app.removeModule('analytics')

// Remove a nested module
app.removeModule('settings.theme')

Other Methods 

getModel 

Returns the model (state tree) of the app.

const model = app.getModel()

flush 

Triggers UI updates based on state changes.

// Standard flush
app.flush()

// Force flush regardless of changes
app.flush(true)

Events 

The app instance is an event emitter that you can subscribe to:

// Listen for a specific event
app.on('flush', (changes) => {
  console.log('State changes:', changes)
})

// Remove an event listener
app.off('flush', myListener)

// Listen once for an event
app.once('initialized', () => {
  console.log('App is ready!')
})

Lifecycle Events 

EventArgumentsDescription
initialized:model-Model has initialized
initialized-App has fully initialized
moduleAddedpath, moduleA module has been added
moduleRemovedpath, moduleA module has been removed
flushchangesState changes have been applied to UI

Sequence Execution Events 

EventArgumentsDescription
startexecution, payloadSequence execution started
endexecution, payloadSequence execution ended
pathStartexecution, payloadPath execution started
pathEndexecution, payloadPath execution ended
functionStartexecution, functionDetails, payloadAction execution started
functionEndexecution, functionDetails, payload, resultAction execution ended
asyncFunctionexecution, functionDetails, payloadAsync action executed
parallelStartexecution, payload, functionsToResolveCountParallel execution started
parallelProgressexecution, payload, functionsStillResolvingCountParallel execution progress update
parallelEndexecution, payload, functionsExecutedCountParallel execution ended
mutationmutationState mutation occurred
rememberdatetimeTime travel occurred (debugging)

Example 

import App from 'cerebral'
import main from './main'

const app = App(main, {
  devtools: process.env.NODE_ENV === 'development' && {
    host: 'localhost:8585',
    reconnect: true
  }
})

// Wait for initialization
app.once('initialized', () => {
  // App is ready to use
  app.getSequence('app.initialize')()

  // Listen for state changes
  app.on('flush', (changes) => {
    console.log('Changes:', changes)
  })
})

See UniversalApp for server-side rendering support.