Skip to main content

Scope

Scope embeds a child reducer in a parent domain by transforming parent state and actions into child state and actions. This is a fundamental tool for breaking down large features into smaller, composable units that can be easier to understand, test, and package into isolated modules.

Type Signature

Initializer

Parameters:
  • toChildState: A writable key path from parent state to a property containing child state
  • toChildAction: A case path from parent action to a case containing child actions
  • child: A reducer builder closure that describes the reducer to run on the child domain

Usage

Basic struct state composition

Enum state composition

Scope also works when state is modeled as an enum:

Multiple child features

You can scope multiple child features in a single parent:

Order of Operations

The order in which you combine Scope with other reducers matters:
Why order matters: When using enum state with case paths, if the parent reducer runs first and switches state to another case, the scoped child reducer won’t be able to react to the action. This can cause subtle bugs. TCA shows a runtime warning and causes test failures when this occurs.

Runtime Warnings

If Scope receives a child action when child state is set to a different case (for enum state), or when the state is unavailable, it will emit a runtime warning:
This typically happens when:
  • A parent reducer changed the state case before the scoped reducer ran
  • An in-flight effect emitted an action when child state was unavailable
  • An action was sent when state was in the wrong case

See Also

  • ifLet - Alternative for optional state that enforces correct ordering
  • forEach - For embedding reducers over collections
  • Reduce - For inline reducer logic