Layout effect
- React Native course
- Intermediate
- Lesson 63/116
- 5 min
Learn the difference between useLayoutEffect and useEffect.
useLayoutEffect
useLayoutEffect has the same signature as useEffect but runs at a different time. The effect is called synchronously, before the browser paints the screen. This is suited for measuring and updating what is visible.
If you measure and immediately change a style, use useLayoutEffect; otherwise the user may see the old state first, then the new one. For most side effects, useEffect is enough.
When to use useLayoutEffect?
In most cases useEffect is the right choice. useLayoutEffect is used only when you measure and need to update in the same paint; for example measuring an element's width and setting its position.
Because useLayoutEffect blocks paint, overusing it hurts performance. Rule of thumb: start with useEffect; switch to useLayoutEffect if you see a visual flicker.
Practice Add useLayoutEffect
Add a useLayoutEffect. Inside it, log console.log('layout') and use an empty dependency array.
Starter code
import React, { useRef } from 'react';
import { View } from 'react-native';
export default function Box() {
const ref = useRef(null);
// Measure with useLayoutEffect
return <View ref={ref} />
}Sample solution
import React, { useRef, useLayoutEffect } from 'react';
import { View } from 'react-native';
export default function Box() {
const ref = useRef(null);
useLayoutEffect(() => {
console.log('layout');
}, []);
return <View ref={ref} />
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 useLayoutEffect signature
useLayoutEffect(() => { measure(); }, ____);
useLayoutEffect(() => { measure(); }, []);
Explanation: An empty array measures once on mount.
2 Effect timing
| Term | Meaning |
|---|---|
useLayoutEffect |
Before paint |
useEffect |
After paint |
mount |
First render |
cleanup |
Before unmount |
3 When does useLayoutEffect run?
- After paint
- Only on unmount
- Before paint Correct answer
- Never
Explanation: It runs synchronously before paint.