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 thedependencies
are not__eq__
to the olddependencies
then thecleanup
function will be called.
This Hook will call the
cleanup
side-effect function with the latest local state fromuse_state()
Hooks.This Hook solves the problem of using
use_effect()
with constant deps to run acleanup
function when a component unmounts. If theuse_effect()
deps are constant so that thecleanup
function only runs once, then thecleanup
function will not have a closure on the latest componentuse_state
state. This Hookcleanup
function will always have a closure on the latest componentuse_state
.The optional
dependencies
argument can be used to trigger the Hook to call thecleanup
function before the component unmounts. Thecleanup
function will be called again when the component unmounts.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.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))