use_effect
Runs a side effect, such as starting a timer or opening a connection, after the component renders, and cleans it up when it is no longer needed.
The setup runs after the component mounts, then again after each render that
dependencies selects. Before it runs again, and when the component unmounts,
the effect's cleanups run: the cleanup the setup returned, then cleanup. They
run once for each time the setup ran, and always finish, in order, before the
setup runs again, even when one of them is async.
A cleanup the setup returns belongs to that setup run, so it sees the same
values the setup saw. cleanup is the function the latest render passed, so it
sees that render's values. Returning the cleanup from the setup is usually what
you want.
Parameters:
- setup (Callable[[], Any | Awaitable[Any]]) - A function that performs the side effect. It may be
async. A non-asyncsetup may return a cleanup function. Anasyncsetup's return value is not used: passcleanupinstead. Anasyncsetup still running when the effect re-runs or the component unmounts is cancelled. - dependencies (Sequence[Any] | None, default:
None) - Values the effect depends on. The effect always runs after the component mounts. If absent, it also re-runs after every render. If empty, it runs only on mount. Otherwise, it re-runs only when one of the dependencies has changed. - cleanup (Callable[[], Any | Awaitable[Any]] | None, default:
None) - A function that cleans up after the effect, run after the cleanup the setup returned. It may beasync.
import asyncio
from datetime import datetime
import flet as ft
@ft.component
def Clock():
now, set_now = ft.use_state(datetime.now())
def start_ticking():
async def tick():
while True:
await asyncio.sleep(1)
set_now(datetime.now())
task = asyncio.create_task(tick())
return task.cancel # stops ticking when Clock unmounts
ft.use_effect(start_ticking, [])
return ft.Text(f"{now:%H:%M:%S}")