Boost Screen Performance with useFocusEffect
Leverage React Navigation's useFocusEffect to run side‑effects only when a screen is active, preventing costly work on background screens.
Insight
When a screen stays mounted while navigating away, any effect that runs on mount (e.g., data fetch, heavy calculations) continues to execute even though the UI isn’t visible. useFocusEffect from @react-navigation/native runs its callback only when the screen gains focus and cleans up on blur, keeping background screens lightweight. This pattern is especially useful for screens with timers, listeners, or expensive async work.
Example
import { useFocusEffect } from '@react-navigation/native';
import { useCallback } from 'react';
function Dashboard() {
useFocusEffect(
useCallback(() => {
const id = setInterval(() => console.log('refresh'), 5000);
return () => clearInterval(id); // cleanup on blur
}, [])
);
return <View><Text>Dashboard</Text></View>;
}
Takeaway
Wrap any effect that should only run while the user is actively viewing a screen in useFocusEffect. It automatically handles mounting/unmounting semantics, reduces background CPU usage, and leads to smoother navigation transitions.