Component state

Views component state

Views comes with a built-in component state system. This system allows you to retrieve and update the state of any Views component from anywhere in your view.
We highly recommend users to use the Views component state for an easy-to-use and opinionated out-of-the-box experience.
Components that have state have a "State API" section in their documentation, for example Table state API.

Register component state

Use the auto-generated id returned by the useComponentState to register the component into the global component state.
In the following example, we pass the id from useComponentState into the TextInput. This registers the text input with the global state and allows us to access its state values, such as value.
const { id, value } = useComponentState();
return <TextInput id={id} defaultValue="Ha" />;
See each component's docs page for documentation on what state values it supports.
Instead of using the autogenerated id, you can also specify your own id in the call to useComponentState and pass the same id into the component.
const { id, value } = useComponentState("my-text-input");
return <TextInput id={id} defaultValue="Ha" />;

Access component state

Retrieve the component state from the return value of useComponentState.
The following example uses the value field on a TextInput's component state in the onClick prop of a Button. Try clicking on the Alert button. See that the input value from the component state is printed in the alert.

Mutate component state

You can also call functions that mutate the state.
The following example adds another Button that appends the string "ha" to the text input's value. Try clicking on the Append button.

Custom, controlled component state

If you would rather manage the Views component state yourself, you can use your state system of choice and treat the Views components as controlled components.
In the following snippet, we rewrite the above example using React's useState hook. We can manually manage the state of the TextInput component using its value and onChange props.

Typescript for type safety

We recommend using Generics to keep the component state type-safe.
In the following example, we tell useComponentState that the component it is registered with is a table. This automatically types state fields such as selectedRow while erroring out on fields that don't exist on the table state such as value.
Most of our examples do not use types for brevity, but we strongly recommend using types throughout your view!