Summary - Lifecycle
- React Native course
- Intermediate
- Lesson 64/116
- 5 min
Combine mount, update and unmount to write a resource manager.
Summary - Lifecycle
The lifecycle has three phases: mount (first render), update (re-render on a state/prop change), and unmount (removal). useEffect unifies all three in one hook.
An empty array runs on mount, a filled array on the relevant change, and no array on every render. Returning a cleanup adds unmount behaviour. Use useLayoutEffect if you see a visual flicker.
Practice Mount and unmount logs
Log console.log('mounted') on mount and console.log('unmounted') as cleanup. Use an empty dependency array.
Starter code
import React from 'react';
import { View } from 'react-native';
export default function Widget() {
// Add mount and unmount logs
return <View />
}Sample solution
import React, { useEffect } from 'react';
import { View } from 'react-native';
export default function Widget() {
useEffect(() => {
console.log('mounted');
return () => {
console.log('unmounted');
};
}, []);
return <View />
}Practice Add useLayoutEffect
Add a useLayoutEffect, log console.log('layout') inside it and use an empty dependency array.
Starter code
import React from 'react';
import { View } from 'react-native';
export default function Bar() {
// Add useLayoutEffect
return <View />
}Sample solution
import React, { useLayoutEffect } from 'react';
import { View } from 'react-native';
export default function Bar() {
useLayoutEffect(() => {
console.log('layout');
}, []);
return <View />
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which array runs only on mount?
- [count]
- no array
- [count, ready]
- [] Correct answer
Explanation: An empty array [] runs only on mount.
2 Lifecycle summary
| Term | Meaning |
|---|---|
mount |
First render |
update |
Re-render |
unmount |
Removal |
useLayoutEffect |
Before paint |