Difference Between useEffect and useLayoutEffect

Atiq ur rehman
1 min readMar 24, 2023

Photo by Count Chris on Unsplash

Both useEffect and useLayoutEffect are hooks in React that allow you to run side-effects in function components.

The main difference between them is the timing of when they run.

useEffect runs after the browser has painted, meaning that it's not blocking the browser from rendering the page. This is useful for any side-effects that don't need to block the rendering process, such as fetching data from an API, logging, or updating state.

useLayoutEffect runs before the browser has painted, meaning that it can potentially block the browser from rendering the page. This can be useful for side-effects that need to be done before the browser paints, such as measuring the size of an element or updating the DOM in a way that affects layout.

Here’s an example to illustrate the difference:

import { useState, useEffect, useLayoutEffect } from 'react';

function Example() {
const [count, setCount] = useState(0);

useEffect(() => {
console.log('useEffect', count);
}, [count]);

useLayoutEffect(() => {
console.log('useLayoutEffect', count);
}, [count]);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Atiq ur rehman
Atiq ur rehman

No responses yet

Write a response