Interview frequency: …
Short answer
Because screens remain in memory in the Stack when navigating forward, a regular useEffect does not run when returning. Use useFocusEffect to run logic each time a screen becomes active and visible.
Explanation
When the user moves from screen A to screen B, screen A stays mounted in the tree so it can be revisited immediately. To refresh data or subscribe to an event when the user returns, use useFocusEffect with useCallback to rerun the code and clean it up when leaving the screen.
Code example
import { useFocusEffect } from '@react-navigation/native';
import { useCallback } from 'react';
function UserProfileScreen() {
useFocusEffect(
useCallback(() => {
// Runs immediately when the screen gains focus
fetchLatestProfileData();
return () => {
// Cleanup function runs when focus is lost
stopPolling();
};
}, [])
);
return <View>{/* ... */}</View>;
}Common mistakes
- Forgetting to wrap the function passed to useFocusEffect in useCallback, causing it to run on every render without stopping.
Follow-up questions
- What strategies improve memory use and prevent screens from accumulating in the Navigation Stack (memory pressure)?
- What is the key difference between Native Stack Navigator and Stack Navigator in React Navigation?