Hooks, Effects & Platform-specific Code

Use React hooks correctly in React Native, write custom hooks, and branch behaviour per platform with Platform and file extensions.

Intermediate · about 8 hours · difficulty 3/5

Learn first: React Native with Expo, TypeScript for App Code, State Fundamentals

Most React Native bugs in real codebases come from misused hooks rather than from native code. Master these and your app becomes far more predictable.

Hooks you use daily

  • useState and useReducer for local state; useReducer when updates depend on several fields.
  • useEffect for synchronising with something outside React: subscriptions, timers, event listeners. Always return a cleanup function.
  • useMemo and useCallback to keep expensive values and callbacks stable, mainly for list items and memoised children. Do not wrap everything.
  • useRef for mutable values that should not trigger renders, and for referencing native views (focus an input).
  • Custom hooks (useDebounce, useAppState) package logic for reuse.

Platform differences

  • Platform.OS and Platform.select({ ios: ..., android: ... }) for small branches.
  • File extensions Button.ios.tsx and Button.android.tsx for larger differences; the bundler picks the right one.
  • AppState tells you when the app goes to the background; BackHandler intercepts the Android back button.

Pitfalls

  • Missing dependencies in effect arrays cause stale values; the ESLint hooks plugin catches these.
  • Fetching data in useEffect without cancellation leads to races; prefer a query library.

Good enough to move on: you can write a custom hook that pauses a timer when the app is backgrounded and cleans up properly.

Key concepts

  • useState and useReducer
  • useEffect and cleanup
  • useMemo, useCallback and memo
  • useRef and imperative handles
  • Custom hooks
  • Platform.select and platform files
  • AppState and BackHandler
  • ESLint rules of hooks

Mini project

Build a focus timer app with a custom useCountdown hook that pauses in the background, resumes correctly, and uses platform-specific haptics.

Check yourself

What happens if a useEffect subscribes to an event listener but never returns a cleanup function?

Free resources