Hooks#

Hooks introduce various features into stateless @component Elements.

Rules of Hooks#

Edifice Hooks imitate React Hooks, and follow the React Rules of Hooks.

The exact same Hooks must be called in exactly the same order on every call to a @component function.

  1. Only call Hooks
    • In the top level of a @component Element render function.

    • In the body of a Custom Hook.

  2. Never call Hooks
    • In a conditional statement.

    • In a loop.

Base Hooks#

use_state(initial_state)

Persistent mutable state Hook inside a @component function.

use_effect(setup[, dependencies])

Side-effect Hook inside a @component function.

use_async(fn_coroutine, dependencies)

Asynchronous side-effect Hook inside a @component function.

Derived Hooks#

Derived Hooks are functions which are written in terms of other Hooks.

These Derived Hooks are provided by Edifice.

use_ref()

Hook for creating a Reference inside a @component function.

use_effect_final(cleanup[, dependencies])

Side-effect Hook for when a @component unmounts.

use_async_call(fn_coroutine)

Hook to call an async function from a non-async context.

use_callback(fn, dependencies)

Hook for a callback function to pass as props.

use_hover()

Hook to track mouse hovering.

use_stop()

This Hook returns a function which will stop the application by calling App.stop().

Custom Hooks#

A “Custom Hook” is just a Derived Hook that is defined in user code.

For example, here is a Custom Hook which provides a clock value. Using this Hook will cause the @component to re-render every second with the clock value incremented each time.

Custom Hook use_clocktick#
def use_clocktick() -> int:
    tick, tick_set = use_state(0)

    async def increment():
        await asyncio.sleep(1)
        tick_set(tick + 1)

    use_async(increment, tick)

    return tick

Use it in a @component Element like this.

Custom Hook use_clocktick usage#
@component
def Clock(self):
    tick = use_clocktick()
    Label(str(tick))