edifice.use_effect_final#

edifice.use_effect_final(cleanup, dependencies=())[source]#

Side-effect Hook for when a @component unmounts.

Parameters:
  • cleanup (Callable[[], None]) – A function of no arguments and no return value.

  • dependencies (Any) – If the dependencies are not __eq__ to the old dependencies then the cleanup function will be called.

This Hook will call the cleanup side-effect function with the latest local state from use_state() Hooks.

This Hook solves the problem of using use_effect() with constant deps to run a cleanup function when a component unmounts. If the use_effect() deps are constant so that the cleanup function only runs once, then the cleanup function will not have a closure on the latest component use_state state. This Hook cleanup function will always have a closure on the latest component use_state.

The optional dependencies argument can be used to trigger the Hook to call the cleanup function before the component unmounts. The cleanup function will be called again when the component unmounts.

use_effect_final#
x, set_x = ed.use_state(0)

def unmount_cleanup_x():
    print(f"At unmount, the value of x is {x}")

use_effect_final(unmount_cleanup_x)

Debounce#

We can use this Hook together with use_async() to “debounce” an effect which must always finally run when the component unmounts.

Debounce#
x, set_x = ed.use_state(0)

# We want to save the value of x to a file whenever the value of
# x changes. But we don't want to do this too often because it would
# lag the GUI responses. Each use_async call will cancel prior
# awaiting calls. So this will save 1 second after the last change to x.

async def save_x_debounce():
    await asyncio.sleep(1.0)
    save_to_file(x)

use_async(save_x_debounce, x)

# And we want to make sure that the final value of x is saved to
# the file when the component unmounts.
# Unmounting the component will cancel the save_x_debounce Task,
# then the use_effect_final will save the final value of x.

use_effect_final(lambda: save_to_file(x))