What is the useEffect hook and common patterns in React Native?
Answer
useEffect in React Native follows the same rules as React web but with some mobile-specific patterns: Data fetching on mount: useEffect(() => { let isMounted = true; async function fetchData() { try { setLoading(true); const data = await api.getUsers(); if (isMounted) setUsers(data); } catch (err) { if (isMounted) setError(err.message); } finally { if (isMounted) setLoading(false); } } fetchData(); return () => { isMounted = false; }; // Cleanup -- prevent setState on unmounted }, []);. Subscribing to app state changes: useEffect(() => { const subscription = AppState.addEventListener("change", nextAppState => { if (nextAppState === "active") { // App came to foreground -- refresh data fetchData(); } }); return () => subscription.remove(); }, []);. Screen focus (React Navigation): import { useFocusEffect } from "@react-navigation/native"; useFocusEffect( useCallback(() => { // Runs when screen is focused fetchData(); return () => { // Cleanup when screen blurs }; }, []) );. Keyboard listeners: useEffect(() => { const showSub = Keyboard.addListener("keyboardDidShow", handleShow); const hideSub = Keyboard.addListener("keyboardDidHide", handleHide); return () => { showSub.remove(); hideSub.remove(); }; }, []);. Hardware back button (Android): useEffect(() => { const backHandler = BackHandler.addEventListener("hardwareBackPress", () => { if (canGoBack) { goBack(); return true; // Prevent default } return false; // Default behavior }); return () => backHandler.remove(); }, [canGoBack]);.
More React Native Questions
View all →- Intermediate What is the React Native New Architecture?
- Intermediate What is React Navigation nested navigators?
- Intermediate How do you handle network requests in React Native?
- Intermediate What are Native Modules in React Native?
- Intermediate What is the difference between react-native-reanimated and the Animated API?