Lesson 5 of 9
Custom Hooks - Mobile-Specific Library
Custom hooks are the primary way to extract and reuse stateful logic in React Native. Building a custom hook library for your app (useFetch, useDebounce, useNetworkStatus, useAppState) prevents duplicating complex subscription and cleanup logic across screens.
useNetworkStatus - Offline Detection
import { useState, useEffect } from 'react';
import NetInfo, { NetInfoState } from '@react-native-community/netinfo';
// npm install @react-native-community/netinfo
interface NetworkStatus {
isConnected: boolean;
isInternetReachable: boolean | null;
type: string;
}
export function useNetworkStatus(): NetworkStatus {
const [status, setStatus] = useState<NetworkStatus>({
isConnected: true,
isInternetReachable: null,
type: 'unknown',
});
useEffect(() => {
// Initial check
NetInfo.fetch().then((state: NetInfoState) => {
setStatus({
isConnected: state.isConnected ?? false,
isInternetReachable: state.isInternetReachable,
type: state.type,
});
});
// Subscribe to changes
const unsubscribe = NetInfo.addEventListener((state: NetInfoState) => {
setStatus({
isConnected: state.isConnected ?? false,
isInternetReachable: state.isInternetReachable,
type: state.type,
});
});
return unsubscribe;
}, []);
return status;
}
// Usage - show offline banner
function App() {
const { isConnected } = useNetworkStatus();
return (
<View style={{ flex: 1 }}>
{!isConnected && (
<View style={{ backgroundColor: '#dc2626', padding: 8 }}>
<Text style={{ color: 'white', textAlign: 'center' }}>No internet connection</Text>
</View>
)}
<AppNavigator />
</View>
);
}useDebounce & useFetch
import { useState, useEffect, useRef, useCallback } from 'react';
// ---- useDebounce - delay value updates (for search inputs) ----
export function useDebounce<T>(value: T, delay: number): T {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer); // cancel if value changes before delay
}, [value, delay]);
return debounced;
}
// Usage: only fetch after user stops typing for 400ms
function SearchScreen() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebounce(query, 400);
useEffect(() => {
if (debouncedQuery.length < 2) return;
performSearch(debouncedQuery);
}, [debouncedQuery]);
}
// ---- useFetch - generic data fetching hook ----
interface FetchResult<T> {
data: T | null;
isLoading: boolean;
error: Error | null;
refetch: () => void;
}
export function useFetch<T>(url: string, options?: RequestInit): FetchResult<T> {
const [data, setData] = useState<T | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const fetchCount = useRef(0); // for cache-busting refetch
const execute = useCallback(() => {
const controller = new AbortController();
setIsLoading(true);
setError(null);
fetch(url, { ...options, signal: controller.signal })
.then(r => { if (!r.ok) throw new Error(`HTTP ${r.status}`); return r.json(); })
.then((d: T) => { setData(d); setIsLoading(false); })
.catch(err => { if (err.name !== 'AbortError') { setError(err); setIsLoading(false); } });
return () => controller.abort();
}, [url, fetchCount.current]);
useEffect(() => { const cleanup = execute(); return cleanup; }, [execute]);
const refetch = useCallback(() => { fetchCount.current++; execute(); }, [execute]);
return { data, isLoading, error, refetch };
}
async function performSearch(q: string) {}useLocalStorage & usePrevious
import AsyncStorage from '@react-native-async-storage/async-storage';
// ---- useAsyncStorage - persist and sync with AsyncStorage ----
export function useAsyncStorage<T>(key: string, defaultValue: T) {
const [value, setValue] = useState<T>(defaultValue);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
AsyncStorage.getItem(key)
.then(stored => {
if (stored !== null) setValue(JSON.parse(stored) as T);
})
.finally(() => setIsLoading(false));
}, [key]);
const store = useCallback(async (newValue: T) => {
setValue(newValue);
await AsyncStorage.setItem(key, JSON.stringify(newValue));
}, [key]);
const remove = useCallback(async () => {
setValue(defaultValue);
await AsyncStorage.removeItem(key);
}, [key, defaultValue]);
return { value, store, remove, isLoading };
}
// Usage
function ThemeSelector() {
const { value: theme, store: setTheme } = useAsyncStorage('theme', 'dark');
return <Switch value={theme === 'dark'} onValueChange={v => setTheme(v ? 'dark' : 'light')} />;
}
// ---- usePrevious - track previous value ----
export function usePrevious<T>(value: T): T | undefined {
const ref = useRef<T | undefined>(undefined);
useEffect(() => { ref.current = value; });
return ref.current;
}
// Usage: detect when count increased
function AnimatedCounter({ count }: { count: number }) {
const prevCount = usePrevious(count);
const increased = prevCount !== undefined && count > prevCount;
// Trigger celebration animation if increased
}Tip
Tip
Practice Custom Hooks MobileSpecific Library in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Encapsulating network status, geolocation, and debounced input in custom hooks
Practice Task
Note
Practice Task - (1) Write a working example of Custom Hooks MobileSpecific Library 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 Custom Hooks MobileSpecific Library 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.
Finished this lesson?