Skip to content

Commit 2dccc8b

Browse files
Improve documentation for component lifecycle events and yield events (#1301)
* Improve documentation for component lifecycle events and yield events Co-Authored-By: Alek Petuskey <[email protected]> * Fix dictionary syntax in code examples to resolve flexdown parser error Co-Authored-By: Alek Petuskey <[email protected]> * Replace yield events section with on_load events documentation Co-Authored-By: Alek Petuskey <[email protected]> * Fix dictionary syntax in on_load example to resolve flexdown parser error Co-Authored-By: Alek Petuskey <[email protected]> * Add Event Reference header to distinguish between explanation and event listing Co-Authored-By: Alek Petuskey <[email protected]> * Fix broken link to page load events documentation and update GitHub stats Co-Authored-By: Alek Petuskey <[email protected]> * Revert changes to GitHub stats in constants.py Co-Authored-By: Alek Petuskey <[email protected]> * Update link format to use Reflex's template system Co-Authored-By: Alek Petuskey <[email protected]> * Fix page load events documentation link to use direct Markdown format Co-Authored-By: Alek Petuskey <[email protected]> * Add events import to fix template reference in documentation Co-Authored-By: Alek Petuskey <[email protected]> * Add detailed explanation of when lifecycle events are activated Co-Authored-By: Alek Petuskey <[email protected]> --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-authored-by: Alek Petuskey <[email protected]> Co-authored-by: Alek Petuskey <[email protected]>
1 parent fe16fb3 commit 2dccc8b

File tree

1 file changed

+112
-4
lines changed

1 file changed

+112
-4
lines changed

docs/api-reference/event_triggers.md

Lines changed: 112 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ from datetime import datetime
44
import reflex as rx
55

66
from pcweb.templates.docpage import docdemo, h1_comp, text_comp, docpage
7+
from pcweb.pages.docs import events
78

89
SYNTHETIC_EVENTS = [
910
{
@@ -92,27 +93,70 @@ SYNTHETIC_EVENTS = [
9293
},
9394
{
9495
"name": "on_mount",
95-
"description": "The on_mount event handler is called after the component is rendered on the page. It is similar to a page on_load event, although it does not necessarily fire when navigating between pages.",
96+
"description": "The on_mount event handler is called after the component is rendered on the page. It is similar to a page on_load event, although it does not necessarily fire when navigating between pages. This event is particularly useful for initializing data, making API calls, or setting up component-specific state when a component first appears.",
9697
"state": """class MountState(rx.State):
9798
events: list[str] = []
99+
data: list[dict] = []
100+
loading: bool = False
98101
99102
@rx.event
100103
def on_mount(self):
101104
self.events = self.events[-4:] + ["on_mount @ " + str(datetime.now())]
105+
106+
@rx.event
107+
async def load_data(self):
108+
# Common pattern: Set loading state, yield to update UI, then fetch data
109+
self.loading = True
110+
yield
111+
# Simulate API call
112+
import asyncio
113+
await asyncio.sleep(1)
114+
self.data = [dict(id=1, name="Item 1"), dict(id=2, name="Item 2")]
115+
self.loading = False
102116
""",
103-
"example": """rx.vstack(rx.foreach(MountState.events, rx.text), on_mount=MountState.on_mount)""",
117+
"example": """rx.vstack(
118+
rx.heading("Component Lifecycle Demo"),
119+
rx.foreach(MountState.events, rx.text),
120+
rx.cond(
121+
MountState.loading,
122+
rx.spinner(),
123+
rx.foreach(
124+
MountState.data,
125+
lambda item: rx.text(f"ID: {item['id']} - {item['name']}")
126+
)
127+
),
128+
on_mount=MountState.on_mount,
129+
)""",
104130
},
105131
{
106132
"name": "on_unmount",
107-
"description": "The on_unmount event handler is called after removing the component from the page. However, on_unmount will only be called for internal navigation, not when following external links or refreshing the page.",
133+
"description": "The on_unmount event handler is called after removing the component from the page. However, on_unmount will only be called for internal navigation, not when following external links or refreshing the page. This event is useful for cleaning up resources, saving state, or performing cleanup operations before a component is removed from the DOM.",
108134
"state": """class UnmountState(rx.State):
109135
events: list[str] = []
136+
resource_id: str = "resource-12345"
137+
status: str = "Resource active"
110138
111139
@rx.event
112140
def on_unmount(self):
113141
self.events = self.events[-4:] + ["on_unmount @ " + str(datetime.now())]
142+
# Common pattern: Clean up resources when component is removed
143+
self.status = f"Resource {self.resource_id} cleaned up"
144+
145+
@rx.event
146+
def initialize_resource(self):
147+
self.status = f"Resource {self.resource_id} initialized"
114148
""",
115-
"example": """rx.vstack(rx.foreach(UnmountState.events, rx.text), on_unmount=UnmountState.on_unmount)""",
149+
"example": """rx.vstack(
150+
rx.heading("Unmount Demo"),
151+
rx.foreach(UnmountState.events, rx.text),
152+
rx.text(UnmountState.status),
153+
rx.link(
154+
rx.button("Navigate Away (Triggers Unmount)"),
155+
href="/docs",
156+
),
157+
on_mount=UnmountState.initialize_resource,
158+
on_unmount=UnmountState.on_unmount,
159+
)""",
116160
},
117161
{
118162
"name": "on_mouse_up",
@@ -270,6 +314,70 @@ These events are triggered by event triggers.
270314

271315
Event triggers are component specific and are listed in the documentation for each component.
272316

317+
## Component Lifecycle Events
318+
319+
Reflex components have lifecycle events like `on_mount` and `on_unmount` that allow you to execute code at specific points in a component's existence. These events are crucial for initializing data, cleaning up resources, and creating dynamic user interfaces.
320+
321+
### When Lifecycle Events Are Activated
322+
323+
- **on_mount**: This event is triggered immediately after a component is rendered and attached to the DOM. It fires:
324+
- When a page containing the component is first loaded
325+
- When a component is conditionally rendered (appears after being hidden)
326+
- When navigating to a page containing the component using internal navigation
327+
- It does NOT fire when the page is refreshed or when following external links
328+
329+
- **on_unmount**: This event is triggered just before a component is removed from the DOM. It fires:
330+
- When navigating away from a page containing the component using internal navigation
331+
- When a component is conditionally removed from the DOM (e.g., via a condition that hides it)
332+
- It does NOT fire when refreshing the page, closing the browser tab, or following external links
333+
334+
## Page Load Events
335+
336+
In addition to component lifecycle events, Reflex also provides page-level events like `on_load` that are triggered when a page loads. The `on_load` event is useful for:
337+
338+
- Fetching data when a page first loads
339+
- Checking authentication status
340+
- Initializing page-specific state
341+
- Setting default values for cookies or browser storage
342+
343+
You can specify an event handler to run when the page loads using the `on_load` parameter in the `@rx.page` decorator or `app.add_page()` method:
344+
345+
```python
346+
class State(rx.State):
347+
data: dict = dict()
348+
349+
@rx.event
350+
def get_data(self):
351+
# Fetch data when the page loads
352+
self.data = fetch_data()
353+
354+
@rx.page(on_load=State.get_data)
355+
def index():
356+
return rx.text('Data loaded on page load')
357+
```
358+
359+
This is particularly useful for authentication checks:
360+
361+
```python
362+
class State(rx.State):
363+
authenticated: bool = False
364+
365+
@rx.event
366+
def check_auth(self):
367+
# Check if user is authenticated
368+
self.authenticated = check_auth()
369+
if not self.authenticated:
370+
return rx.redirect('/login')
371+
372+
@rx.page(on_load=State.check_auth)
373+
def protected_page():
374+
return rx.text('Protected content')
375+
```
376+
377+
For more details on page load events, see the [page load events documentation]({events.page_load_events.path}).
378+
379+
# Event Reference
380+
273381
```python eval
274382
rx.box(
275383
rx.divider(),

0 commit comments

Comments
 (0)