Skip to main content

Lesson 9 of 9

Practice & Quiz - Hooks in React Native

Test your mastery of custom hooks for mobile including useNetworkStatus, useAppState, and useDebounce with a practical exercise and 5 quiz questions.

10 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Practical Exercise - useNetworkStatus + useAppState Hooks

Practical Exercise - useNetworkStatus + useAppState Hooks
import { useState, useEffect, useRef, useCallback } from 'react';
import NetInfo, { NetInfoState } from '@react-native-community/netinfo';
import { AppState, AppStateStatus } from 'react-native';

// ─── useNetworkStatus - monitors online/offline with type ──────
interface NetworkStatus {
  isConnected: boolean;
  type: string;  // 'wifi' | 'cellular' | 'none' | 'unknown'
}

export function useNetworkStatus(): NetworkStatus {
  const [status, setStatus] = useState<NetworkStatus>({
    isConnected: true,
    type: 'unknown',
  });

  useEffect(() => {
    // fetch() initial state
    NetInfo.fetch().then((state: NetInfoState) => {
      setStatus({
        isConnected: state.isConnected ?? true,
        type: state.type,
      });
    });

    // subscribe to future changes
    const unsubscribe = NetInfo.addEventListener((state: NetInfoState) => {
      setStatus({
        isConnected: state.isConnected ?? true,
        type: state.type,
      });
    });

    return unsubscribe;  // cleanup removes listener
  }, []);

  return status;
}

// ─── useAppState - tracks foreground/background transitions ───
export function useAppState(): AppStateStatus {
  const [appState, setAppState] = useState<AppStateStatus>(
    AppState.currentState
  );

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

  return appState;
}

// ─── useOnForeground - runs callback when app comes to foreground ─
export function useOnForeground(callback: () => void) {
  const appState = useAppState();
  const prevState = useRef<AppStateStatus>(appState);
  const stableCallback = useRef(callback);
  stableCallback.current = callback; // always up-to-date without adding to deps

  useEffect(() => {
    if (prevState.current !== 'active' && appState === 'active') {
      stableCallback.current();
    }
    prevState.current = appState;
  }, [appState]);
}

// ─── Usage ─────────────────────────────────────────────────────
function SyncBanner() {
  const { isConnected, type } = useNetworkStatus();

  useOnForeground(() => {
    if (isConnected) {
      console.log('App foregrounded and online - syncing data...');
    }
  });

  if (isConnected) return null;
  return (
    <View style={{ backgroundColor: '#ef4444', padding: 8 }}>
      <Text style={{ color: '#fff', textAlign: 'center' }}>
        No internet connection ({type})
      </Text>
    </View>
  );
}

Module Quiz

Module Quiz
Question 1 of 5

Why store a callback in `useRef` instead of adding it to useEffect's dependency array?

Tip

Tip

Practice Practice Quiz Hooks in React Native in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Module 5 Knowledge Check: Mobile lifecycle, memoization, and custom hooks

Practice Task

Note

Practice Task - (1) Write a working example of Practice Quiz Hooks in React Native 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.

Common Mistake

Warning

A common mistake with Practice Quiz Hooks in React Native 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