0
# Lifecycle Management
1
2
React hooks and utilities for managing page lifecycle events and navigation state in mobile applications, providing fine-grained control over component behavior during page transitions.
3
4
## Capabilities
5
6
### Page Lifecycle Hooks
7
8
Hooks for responding to page navigation events in mobile applications.
9
10
```typescript { .api }
11
/**
12
* Hook that fires when a page has fully entered and is now the active page.
13
* This will fire whether it was the first load or a page being returned to.
14
* @param callback - Function to execute when page enters
15
* @param deps - Dependency array for the callback (similar to useEffect)
16
*/
17
function useIonViewDidEnter(
18
callback: LifeCycleCallback,
19
deps?: any[]
20
): void;
21
22
/**
23
* Hook that fires when a page is about to enter and become the active page.
24
* This will fire whether it was the first load or a page being returned to.
25
* @param callback - Lifecycle callback that can return a cleanup function
26
* @param deps - Dependency array for the callback
27
*/
28
function useIonViewWillEnter(
29
callback: LifeCycleCallback,
30
deps?: any[]
31
): void;
32
33
/**
34
* Hook that fires when a page has fully left and is no longer the active page.
35
* This will fire when navigating to a new page or when the current page is being destroyed.
36
* @param callback - Lifecycle callback that can return a cleanup function
37
* @param deps - Dependency array for the callback
38
*/
39
function useIonViewDidLeave(
40
callback: LifeCycleCallback,
41
deps?: any[]
42
): void;
43
44
/**
45
* Hook that fires when a page is about to leave and no longer be the active page.
46
* This will fire when navigating to a new page or when the current page is being destroyed.
47
* @param callback - Lifecycle callback that can return a cleanup function
48
* @param deps - Dependency array for the callback
49
*/
50
function useIonViewWillLeave(
51
callback: LifeCycleCallback,
52
deps?: any[]
53
): void;
54
55
/**
56
* Lifecycle callback interface that supports returning cleanup functions.
57
*/
58
interface LifeCycleCallback {
59
(): void | (() => void | undefined);
60
id?: number;
61
}
62
```
63
64
### Higher-Order Component
65
66
Higher-order component for adding lifecycle functionality to class components.
67
68
```typescript { .api }
69
/**
70
* Higher-order component that adds Ionic lifecycle methods to class components.
71
* Adds ionViewDidEnter, ionViewWillEnter, ionViewDidLeave, and ionViewWillLeave methods.
72
* @param WrappedComponent - Component to wrap with lifecycle functionality
73
* @returns Enhanced component with lifecycle methods
74
*/
75
function withIonLifeCycle<P extends object>(
76
WrappedComponent: React.ComponentType<P>
77
): React.ComponentType<P>;
78
```
79
80
### Lifecycle Context
81
82
Context provider and consumer for managing lifecycle state across components.
83
84
```typescript { .api }
85
/**
86
* Context interface for managing lifecycle callbacks and state.
87
*/
88
interface IonLifeCycleContextInterface {
89
/** Register a callback for the ionViewDidEnter event */
90
onIonViewDidEnter: (callback: LifeCycleCallback) => void;
91
/** Trigger ionViewDidEnter event */
92
ionViewDidEnter: () => void;
93
/** Register a callback for the ionViewWillEnter event */
94
onIonViewWillEnter: (callback: LifeCycleCallback) => void;
95
/** Trigger ionViewWillEnter event */
96
ionViewWillEnter: () => void;
97
/** Register a callback for the ionViewDidLeave event */
98
onIonViewDidLeave: (callback: LifeCycleCallback) => void;
99
/** Trigger ionViewDidLeave event */
100
ionViewDidLeave: () => void;
101
/** Register a callback for the ionViewWillLeave event */
102
onIonViewWillLeave: (callback: LifeCycleCallback) => void;
103
/** Trigger ionViewWillLeave event */
104
ionViewWillLeave: () => void;
105
/** Cleanup callbacks */
106
cleanupIonViewDidEnter: (callback: LifeCycleCallback) => void;
107
cleanupIonViewWillEnter: (callback: LifeCycleCallback) => void;
108
cleanupIonViewDidLeave: (callback: LifeCycleCallback) => void;
109
cleanupIonViewWillLeave: (callback: LifeCycleCallback) => void;
110
}
111
112
/**
113
* Default implementation of the lifecycle context.
114
* Provides methods for managing lifecycle callbacks.
115
*/
116
class DefaultIonLifeCycleContext implements IonLifeCycleContextInterface {
117
onIonViewDidEnter(callback: LifeCycleCallback): void;
118
ionViewDidEnter(): void;
119
onIonViewWillEnter(callback: LifeCycleCallback): void;
120
ionViewWillEnter(): void;
121
onIonViewDidLeave(callback: LifeCycleCallback): void;
122
ionViewDidLeave(): void;
123
onIonViewWillLeave(callback: LifeCycleCallback): void;
124
ionViewWillLeave(): void;
125
cleanupIonViewDidEnter(callback: LifeCycleCallback): void;
126
cleanupIonViewWillEnter(callback: LifeCycleCallback): void;
127
cleanupIonViewDidLeave(callback: LifeCycleCallback): void;
128
cleanupIonViewWillLeave(callback: LifeCycleCallback): void;
129
}
130
131
/**
132
* React context for providing lifecycle functionality throughout the component tree.
133
*/
134
const IonLifeCycleContext: React.Context<IonLifeCycleContextInterface>;
135
```
136
137
**Usage Examples:**
138
139
```typescript
140
import React, { useState, useEffect } from 'react';
141
import {
142
useIonViewDidEnter,
143
useIonViewWillEnter,
144
useIonViewDidLeave,
145
useIonViewWillLeave,
146
withIonLifeCycle
147
} from '@ionic/react';
148
149
// Functional component with lifecycle hooks
150
const HomePage: React.FC = () => {
151
const [data, setData] = useState<any[]>([]);
152
const [isActive, setIsActive] = useState(false);
153
154
// Load data when page is about to enter
155
useIonViewWillEnter(() => {
156
console.log('Page will enter - preparing data');
157
loadInitialData();
158
});
159
160
// Start timers/subscriptions when page has entered
161
useIonViewDidEnter(() => {
162
console.log('Page did enter - starting background tasks');
163
setIsActive(true);
164
startPeriodicRefresh();
165
}, []);
166
167
// Clean up when page is about to leave
168
useIonViewWillLeave(() => {
169
console.log('Page will leave - stopping background tasks');
170
setIsActive(false);
171
stopPeriodicRefresh();
172
});
173
174
// Final cleanup when page has left
175
useIonViewDidLeave(() => {
176
console.log('Page did leave - final cleanup');
177
clearCache();
178
});
179
180
const loadInitialData = async () => {
181
try {
182
const response = await fetch('/api/data');
183
const result = await response.json();
184
setData(result);
185
} catch (error) {
186
console.error('Failed to load data:', error);
187
}
188
};
189
190
const startPeriodicRefresh = () => {
191
// Start interval or subscription
192
};
193
194
const stopPeriodicRefresh = () => {
195
// Stop interval or subscription
196
};
197
198
const clearCache = () => {
199
// Clear any cached data
200
setData([]);
201
};
202
203
return (
204
<IonPage>
205
<IonHeader>
206
<IonToolbar>
207
<IonTitle>Home {isActive && '(Active)'}</IonTitle>
208
</IonToolbar>
209
</IonHeader>
210
<IonContent>
211
{data.map((item, index) => (
212
<IonItem key={index}>
213
<IonLabel>{item.name}</IonLabel>
214
</IonItem>
215
))}
216
</IonContent>
217
</IonPage>
218
);
219
};
220
221
// Class component with lifecycle HOC
222
interface ProfilePageProps {
223
userId: string;
224
}
225
226
interface ProfilePageState {
227
profile: any;
228
loading: boolean;
229
}
230
231
class ProfilePageComponent extends React.Component<ProfilePageProps, ProfilePageState> {
232
private refreshInterval?: NodeJS.Timeout;
233
234
constructor(props: ProfilePageProps) {
235
super(props);
236
this.state = {
237
profile: null,
238
loading: false
239
};
240
}
241
242
ionViewWillEnter() {
243
console.log('Profile page will enter');
244
this.loadProfile();
245
}
246
247
ionViewDidEnter() {
248
console.log('Profile page did enter');
249
this.startAutoRefresh();
250
}
251
252
ionViewWillLeave() {
253
console.log('Profile page will leave');
254
this.stopAutoRefresh();
255
}
256
257
ionViewDidLeave() {
258
console.log('Profile page did leave');
259
// Additional cleanup if needed
260
}
261
262
loadProfile = async () => {
263
this.setState({ loading: true });
264
try {
265
const response = await fetch(`/api/profile/${this.props.userId}`);
266
const profile = await response.json();
267
this.setState({ profile, loading: false });
268
} catch (error) {
269
console.error('Failed to load profile:', error);
270
this.setState({ loading: false });
271
}
272
};
273
274
startAutoRefresh = () => {
275
this.refreshInterval = setInterval(() => {
276
this.loadProfile();
277
}, 30000); // Refresh every 30 seconds
278
};
279
280
stopAutoRefresh = () => {
281
if (this.refreshInterval) {
282
clearInterval(this.refreshInterval);
283
this.refreshInterval = undefined;
284
}
285
};
286
287
render() {
288
const { profile, loading } = this.state;
289
290
return (
291
<IonPage>
292
<IonHeader>
293
<IonToolbar>
294
<IonTitle>Profile</IonTitle>
295
</IonToolbar>
296
</IonHeader>
297
<IonContent>
298
{loading && <IonSpinner />}
299
{profile && (
300
<IonCard>
301
<IonCardHeader>
302
<IonCardTitle>{profile.name}</IonCardTitle>
303
</IonCardHeader>
304
<IonCardContent>
305
<p>{profile.email}</p>
306
<p>{profile.bio}</p>
307
</IonCardContent>
308
</IonCard>
309
)}
310
</IonContent>
311
</IonPage>
312
);
313
}
314
}
315
316
// Wrap class component with lifecycle HOC
317
const ProfilePage = withIonLifeCycle(ProfilePageComponent);
318
319
// Custom hook combining lifecycle with other logic
320
const usePageAnalytics = (pageName: string) => {
321
useIonViewDidEnter(() => {
322
// Track page view
323
analytics.track('page_view', { page: pageName });
324
});
325
326
useIonViewDidLeave(() => {
327
// Track page exit
328
analytics.track('page_exit', { page: pageName });
329
});
330
};
331
332
// Usage of custom hook
333
const AnalyticsPage: React.FC = () => {
334
usePageAnalytics('dashboard');
335
336
return (
337
<IonPage>
338
<IonContent>
339
<h1>Dashboard</h1>
340
</IonContent>
341
</IonPage>
342
);
343
};
344
```
345
346
## Lifecycle Event Sequence
347
348
The lifecycle events fire in the following sequence during navigation:
349
350
**When entering a page:**
351
1. `ionViewWillEnter` - Page is about to enter
352
2. `ionViewDidEnter` - Page has entered and is now active
353
354
**When leaving a page:**
355
1. `ionViewWillLeave` - Page is about to leave
356
2. `ionViewDidLeave` - Page has left and is no longer active
357
358
## Best Practices
359
360
1. **Data Loading**: Use `useIonViewWillEnter` for initial data loading to ensure it's ready when the page appears
361
2. **Subscriptions**: Start subscriptions in `useIonViewDidEnter` and clean them up in `useIonViewWillLeave`
362
3. **Timers**: Use lifecycle hooks to manage timers and intervals to avoid memory leaks
363
4. **Analytics**: Track page views and user interactions using lifecycle events
364
5. **Performance**: Clean up heavy operations when pages become inactive to improve performance