useEffect vs useLayoutEffect in React Native: When to Choose Which
A quick guide to the subtle timing differences between useEffect and useLayoutEffect in React Native, and how the right choice can prevent UI flicker and layout bugs.
Insight
In React Native, useEffect runs after the render is painted, while useLayoutEffect runs synchronously after the DOM (or native view hierarchy) is updated but before the frame is committed. This makes useLayoutEffect ideal for measuring layout, adjusting scroll positions, or synchronously updating refs that affect the UI. Using useEffect for these tasks can cause a visible flicker because the UI updates once, then re‑renders after the effect runs.
Example
import { useLayoutEffect, useRef } from 'react';
import { ScrollView } from 'react-native';
export default function Chat() {
const scrollRef = useRef<ScrollView>(null);
// Scroll to bottom as soon as new messages are rendered
useLayoutEffect(() => {
scrollRef.current?.scrollToEnd({ animated: false });
}, [/* messages dependency */]);
return <ScrollView ref={scrollRef}>{/* messages */}</ScrollView>;
}
Takeaway
Reserve useLayoutEffect for layout‑dependent side effects that must happen before the frame is displayed. For data fetching, subscriptions, or non‑visual work, stick with useEffect to keep the UI responsive and avoid unnecessary re‑paints.