
In this article, we'll dive into the specifics of two important hooks in React: useEffect and useLayoutEffect. We will learn about their usage, differences, and how to choose between them for different scenarios.
What is useEffect?#
The useEffect hook lets you perform side effects in functional components. Side effects refer to any operation that interacts with the outside environment, such as data fetching, subscriptions, timers, logging, and manual DOM manipulations.
Syntax:
useEffect(didUpdate [inputs]);
Example:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the example above, after every render, the function provided to useEffect updates the document title.
What is useLayoutEffect?#
The useLayoutEffect is almost identical to useEffect but it fires synchronously after all DOM mutations. Use this to read the layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously before the browser has a chance to paint.
Syntax:
useLayoutEffect(didUpdate [inputs]);
Example:
import React, { useLayoutEffect } from 'react';
function Example() {
useLayoutEffect(() => {
// Manipulate the DOM in here
}, []);
return <div>Hello, world!</div>;
}
Differences Between useEffect and useLayoutEffect#
- Execution Timing:
useEffectruns asynchronously and after a render is painted to the screen.useLayoutEffect, on the other hand, runs synchronously immediately after React has performed all DOM mutations. This means if you're making DOM changes, you could cause a synchronous re-render by modifying the state. - Visual Effects: If causing a visual update, use
useLayoutEffectto avoid flickering. When usinguseEffect, components get rendered first with DOM mutations and get updated later whenuseEffectis called. - Server Rendering:
useEffectdoes not run on server rendering whileuseLayoutEffectdoes. However, this results in a warning, since the effect tries to update after the component has already been sent to client.
Ultimately, the rule of thumb is to prefer useEffect unless there is a compelling reason or specific scenario that requires useLayoutEffect.
That's it! You're now equipped with a solid understanding of useEffect and useLayoutEffect. Happy coding!
References: