The Reaction
function creates a declarative way to react to state changes outside the normal component rendering flow.
Reaction(dependencies, callback)
dependencies (Object): An object where keys define the property names in the callback’s argument, and values are tags pointing to state paths. Optional - if omitted, the first argument is treated as the callback.
callback (Function): A function called when tracked state changes. Receives an object containing:
get
function to access additional state valuesA reaction object with the following methods:
create(controller, modulePath, name): Binds the reaction to a controller/app and associates it with a module.
controller
: The Cerebral app/controllermodulePath
: Array specifying the module path (e.g., ['users']
)name
: String identifier for debugginginitialize(): Registers the reaction with the dependency system.
onUpdate(): Manually triggers the reaction callback.
destroy(): Cleans up the reaction by unregistering it from the dependency system.
Basic usage:
import { Reaction, state } from 'cerebral'
const logUser = Reaction(
{
user: state`user`,
count: state`count`
},
({ user, count, get }) => {
console.log(`User: ${user.name}, Count: ${count}`)
// Access additional state using get
const otherValue = get(state`otherPath`)
}
)
When using components with Cerebral, a reaction
prop is provided to create and manage reactions:
// Class components
this.props.reaction(
'debugName', // Optional name for debugging
{ error: state`usernameError` }, // Dependencies
({ error }) => {
/* callback */
} // Callback
)
// Function components
reaction('debugName', { error: state`usernameError` }, ({ error }) => {
/* callback */
})
Component reactions are automatically disposed when the component unmounts.
For usage patterns and examples, see the reactions guide.