Skip to content

UseState

UseState is a hook that allows to declare state variables and manipulate its value, which in turn notifies about its changes to listeners.

Syntax

UseState<T>(T initialValue);

UseState accepts this argument:

  • initialValue: Initial value of T type that it will hold.

Properties & Methods

UseState provides the following properties and methods:

  • value: A getter/setter that allows to read and write its state.
  • Methods inherited from ReactterState (Learn more here):

    • update : A method to notify changes after run a set of instructions.
    • refresh : A method to force to notify changes.
    • * bind : A method to bind an instance to it.
    • * unbind : A method to unbind an instance to it.
    • * dispose : A method to remove all listeners and free resources.

Usage

Declaration

UseState can be initialized using the constructor class:

final intState = UseState<int>(0);
final strState = UseState("initial value");
final userState = UseState(User());

Reading and writing the value

UseState has a value property that allows to read and write its state:

intState.value = 10;
print("Current state: ${intState.value}");

Updating the state

Use update method to notify changes after run a set of instructions:

uState.update((value) {
uState.value = "New value";
});

Use refresh method to force to notify changes.

userState.refresh();

Listening to changes

When value has changed, the UseState will emit the following events(learn about it here):

  • Lifecycle.willUpdate event is triggered before the value change or update , refresh methods have been invoked.
  • Lifecycle.didUpdate event is triggered after the value change or update , refresh methods have been invoked.

Example of listening to changes:

1
Reactter.on(
2
myState,
3
Lifecycle.didUpdate,
4
(_, state) => print("State value has changed to: ${state.value}"),
5
);