Skip to main content

Using State

Import

import { State } from "carry-on-react";

Basic usage

Default store

The child node of a State component is a render function. The render function is given the store state as it's first parameter.

Live Editor
Result
Loading...

Named store

A named store can be accessed using the from property:

Live Editor
Result
Loading...

Use Hook

Functional components have the useCarryOn hook to access state.

Live Editor
Result
Loading...

Access tracking

When using the State component, selectors indicating which fields should be subscribed to are optional. This is because when the render function executes the state is monitored for usage via a Proxy. The usage tracking is then used to determine which state fields will cause the State component to update.

In the next example, the first State component will update when field1 changes, and the second State component will update when field2 changes.

Live Editor
Result
Loading...

Strict

The list of monitored state fields does not change once created. You can force every render to be monitored by specifying the strict property.

Live Editor
Result
Loading...

Constant

If the state needed is constant, the constant property will prevent any render updates after the first render.

Live Editor
Result
Loading...

Path

A string path property can be used to choose a specific object or value. Dotted paths and indexes are supported.

Live Editor
Result
Loading...

Select

An optional selector can be used with the select property. When the select property is used, access tracking will be applied to the select function and not the render function.

Live Editor
Result
Loading...

Default value

The default property lets you subsitute a default state value when the store state specified by the path property is undefined.

Live Editor
Result
Loading...

Delayed updates

In some cases, state change updates may arrive too quickly for a component to sensibly make use of. The throttle and debounce properties will apply the corresponding delay to any state change updates a State component is subscribed to.

Throttle

Live Editor
Result
Loading...

Debounce

Live Editor
Result
Loading...

Debugging

Three properties are available for debugging. Debug messages are sent to the console.

debug will log debug messages. verbose will log verbose debug messages. id will set an identifier to include in the log messages.

Live Editor
Result
Loading...

Global Debugging

Debugging can be turned on or off for all State components:

State.Debug = true;
State.Verbose = true;

Lifecycle Events

Use the onMount and onUnmount properties when you need to execute actions during those lifecycle events.

Live Editor
Result
Loading...