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
useStateanduseReducerfor local state;useReducerwhen updates depend on several fields.useEffectfor synchronising with something outside React: subscriptions, timers, event listeners. Always return a cleanup function.useMemoanduseCallbackto keep expensive values and callbacks stable, mainly for list items and memoised children. Do not wrap everything.useReffor 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.OSandPlatform.select({ ios: ..., android: ... })for small branches.- File extensions
Button.ios.tsxandButton.android.tsxfor larger differences; the bundler picks the right one. AppStatetells you when the app goes to the background;BackHandlerintercepts the Android back button.
Pitfalls
- Missing dependencies in effect arrays cause stale values; the ESLint hooks plugin catches these.
- Fetching data in
useEffectwithout 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
- React: Built-in hooks (React)
- React Native: Platform-specific code (React Native)
- React: You might not need an effect (React)