📱 React Native Intermediate

What is the useEffect hook and common patterns in React Native?

Why Interviewers Ask This

This tests whether you can apply React Native knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

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]);.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real React Native project.