Hooks

useState

This is the most basic hook which allows you to create an instance of a value which can be both read and updated in your component's code, the state is kept between renders and any updates to it will cause it to re-render by default.

Component(fun ctx ->
    let state = ctx.useState 0
    
    // state var that does not rerender on change
    let state = ctx.useState (0, renderOnChange = false)
    
    // Component's UI
)

useEffect

Sometimes you need to subscribe to an observable, to an IWritable<'T>, create a disposable value, or make some logging. For these and other scenarios you can use the useEffect hook.

This hook requires a handler which is a function that can return unit or IDisposable depending on your needs. For cases where you need to handle subscriptions the second will be better.

This hook also asks for a triggers list, these help Avalonia.FuncUI to decide when to run the handler function. The possible trigger values are defined as follows:

[<RequireQualifiedAccess>]
type EffectTrigger =
    /// triggers the effect to run every time after the passed dependency has changed.
    | AfterChange of state: IAnyReadable
    /// triggers the effect to run once after the component initially rendered.
    | AfterInit
    /// triggers the effect to run every time after the component is rendered.
    | AfterRender

For example if we had to fetch some resources from a server after the component is initialized we would do something like the following:

We can also re-execute these handlers if we make them dependent on any readable values, for example let us try to compute the sum of the ages of a user list whenever the user list changes.

IReadable<'T>

As is in the source comments:

Readable state value that can be subscribed to.

Readables are values to which you can subscribe to get updates, these are commonly used values.

An example would be the following:

At this point this component will be pretty much static, it won't ever be re-rendered because there are no changes to its state.

IWritable<'T>

As is in the source comments:

Readable and writable state value that can be subscribed to.

If we take the previous example and add mutations, it would look like the following:

Passed Values

Sometimes when you already have an IWritable<'T> value, you would like to use it on sibling components so they can show the same data in different formats, or just to communicate changes between different component trees without having to drill the values into the component's tree.

For that we can use Passed Values.

Last updated