Skip to main content

Lesson 2 of 9

useEffect - Mobile-Specific Patterns

useEffect on mobile has unique challenges: the app can be backgrounded at any time, subscriptions must be cleaned up on unmount, network fetches can race if a user navigates quickly, and effects inside FlatList items run per-item (thousands of effects).

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Race Condition Prevention & Cleanup

Race Condition Prevention & Cleanup
import { useEffect, useState } from 'react';

// ---- Race condition: user navigates away before fetch completes ----
function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    let isMounted = true;           // flag to track mount status
    const controller = new AbortController();

    fetch(`/api/users/${userId}`, { signal: controller.signal })
      .then(r => r.json())
      .then(data => {
        if (isMounted) setUser(data);  // only update if still mounted
      })
      .catch(err => {
        if (err.name !== 'AbortError') console.error(err);
      });

    return () => {
      isMounted = false;
      controller.abort();             // cancel in-flight request
    };
  }, [userId]);                       // re-runs when userId changes
}

// ---- AppState - respond to background/foreground ----
import { AppState, AppStateStatus } from 'react-native';

function useAppState() {
  const [appState, setAppState] = useState<AppStateStatus>(AppState.currentState);

  useEffect(() => {
    const subscription = AppState.addEventListener('change', nextState => {
      setAppState(nextState);
    });
    return () => subscription.remove();
  }, []);

  return appState;
}

// ---- Pause polling when app is backgrounded ----
function LiveScoreboard({ matchId }: { matchId: string }) {
  const appState = useAppState();
  const [score, setScore] = useState(null);

  useEffect(() => {
    if (appState !== 'active') return; // don't poll when backgrounded

    const interval = setInterval(() => {
      fetchScore(matchId).then(setScore);
    }, 5000);

    return () => clearInterval(interval); // always clean up
  }, [matchId, appState]);
}

async function fetchScore(matchId: string) { return {}; }

Tip

Tip

Practice useEffect MobileSpecific Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Handling component mount/unmount and iOS/Android app background transitions

Practice Task

Note

Practice Task - (1) Write a working example of useEffect MobileSpecific Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with useEffect MobileSpecific Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done