Understanding the Difference Between useEffect and useLayoutEffect in React Native
Harshit Pandey
React Native | JavaScript | Typescript | Android | IOS | DSA | Node JS
When building mobile apps with React Native, you often need to run side effects like fetching data, setting up event listeners, or measuring layout sizes. React Native provides two powerful hooks for handling side effects:
What is useEffect in React Native?
useEffect runs asynchronously after the component has rendered and the UI is visible to the user. It doesn't block the UI, making it ideal for non-UI-related tasks.
Common Use Cases for useEffect in React Native
import React, { useEffect, useState } from 'react';
import { View, Text, Button } from 'react-native';
const ExampleScreen = () => {
const [count, setCount] = useState(0);
useEffect(() => {
console.log('useEffect - Count:', count);
}, [count]);
return (
<View>
<Text>Count: {count}</Text>
<Button title="Increment" onPress={() => setCount(count + 1)} />
</View>
);
};
When useEffect Runs in React Native
What is useLayoutEffect in React Native?
useLayoutEffect runs synchronously after all DOM mutations (in React Native’s case, after the native view tree updates) but before the UI is painted to the screen. It blocks the UI rendering until it completes, which is useful for layout measurements and animations.
Common Use Cases for useLayoutEffect in React Native
import React, { useLayoutEffect, useRef, useState } from 'react';
import { View, Text } from 'react-native';
const LayoutExample = () => {
const [width, setWidth] = useState(0);
const viewRef = useRef<View>(null);
useLayoutEffect(() => {
if (viewRef.current) {
viewRef.current.measure((x, y, width) => {
setWidth(width);
});
}
}, []);
return (
<View>
<View ref={viewRef} style={{ width: '80%', height: 100, backgroundColor: 'skyblue' }} />
<Text>Width: {width}px</Text>
</View>
);
};
When useLayoutEffect Runs in React Native
When to Use Which Hook in React Native?
? Use useEffect When:
? Use useLayoutEffect When: