useEffect lifecycle
- React Native course
- Intermediate
- Lesson 62/116
- 5 min
Learn lifecycle with useEffect.
useEffect as lifecycle
useEffect merges the three lifecycle methods of class components (componentDidMount, componentDidUpdate, componentWillUnmount) into a single hook. The dependency array decides when it runs.
An empty array [] runs only on mount; a filled array [a, b] runs on mount and when a or b changes; no array runs on every render. Returning a cleanup adds unmount behaviour.
Practice Track userId changes
Add a useEffect. Inside it, log console.log('user: ' + userId) and put userId in the dependency array.
Starter code
import React from 'react';
import { Text } from 'react-native';
export default function Profile({ userId }) {
// Log when userId changes
return <Text>{userId}</Text>;
}Sample solution
import React, { useEffect } from 'react';
import { Text } from 'react-native';
export default function Profile({ userId }) {
useEffect(() => {
console.log('user: ' + userId);
}, [userId]);
return <Text>{userId}</Text>;
}Three behaviours
useEffect offers three core behaviours. Empty array for mount only; a filled array for a changing value; no array for every render. A cleanup can be returned in any case.
These three behaviours let you tune side effects to the lifecycle with a single hook. Picking the right array prevents unnecessary runs and leaks.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you provide no dependency array?
- Runs only on mount
- Runs on every render Correct answer
- Runs only on unmount
- Never runs
Explanation: With no array, the effect runs on every render.
2 Track count changes
useEffect(() => { save(count); }, [____]);
useEffect(() => { save(count); }, [count]);
Explanation: The [count] array tracks count changes.
3 Match array behaviour
| Term | Meaning |
|---|---|
[] |
Mount only |
[count] |
Mount + count change |
no array |
Every render |
cleanup |
Before unmount |