Discover the Secrets of React Hook’s useEffect & useLayoutEffect and When to Use Them

Mohamed Khan
Reflex Media
Published in
5 min readFeb 13, 2023

If you’re a seasoned React developer, you’ve probably heard of hooks. Hooks are a way to add state and side effects to functional components, and they’ve been a game changer for React development. In this article, we’re going to dive deep into two of the most powerful hooks in React: useEffect and useLayoutEffect.

Photo by Lautaro Andreani on Unsplash

Note that this article is not about explaining what React Hooks, useEffect, and useLayoutEffect are, but about understanding the mechanics behind them and making better decisions on when to use which. If you are new to React Hooks, there are many great articles out there. Come back here once you have a fair understanding of them!

Let’s get started!

For the purpose of this demo, let’s create a simple button that allows a user to click on it and display a message at the bottom. Let’s use useEffect, as what most developers would natively start with.

import { useEffect, useState } from "react";
import "./App.css";

const longText = `What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printinand typesetting industry. Lorem Ipsum has been the industry's standardummy text ever since the 1500s, when an unknown printer took a galleof type and scrambled it to make a type specimen book. It has survivenot only five centuries, but also the leap into electronic typesettingremaining essentially unchanged. It was popularised in the 1960s witthe release of Letraset sheets containing Lorem Ipsum passages, and morrecently with desktop publishing software like Aldus PageMaker includinversions of Lorem Ipsum. Why do we use it? It is a long established facthat a reader will be distracted by the readable content of a page whelooking at its layout. The point of using Lorem Ipsum is that it has more-or-less normal distribution of letters, as opposed to usin'Content here, content here', making it look like readable English. Mandesktop publishing packages and web page editors now use Lorem Ipsum atheir default model text, and a search for 'lorem ipsum' will uncovemany web sites still in their infancy. Various versions have evolveover the years, sometimes by accident, sometimes on purpose (injectedhumour and the like). Where does it come from? Contrary to populabelief, Lorem Ipsum is not simply random text. It has roots in a piecof classical Latin literature from 45 BC, making it over 2000 years oldRichard McClintock, a Latin professor at Hampden-Sydney College iVirginia, looked up one of the more obscure Latin words, consecteturfrom a Lorem Ipsum passage, and going through the cites of the word iclassical literature, discovered the undoubtable source. Lorem Ipsucomes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum eMalorum" (The Extremes of Good and Evil) by Cicero, written in 45 BCThis book is a treatise on the theory of ethics, very popular during thRenaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor siamet..", comes from a line in section 1.10.32. The standard chunk oLorem Ipsum used since the 1500s is reproduced below for thosinterested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum eMalorum" by Cicero are also reproduced in their exact original formaccompanied by English versions from the 1914 translation by H. RackhamWhere can I get some? There are many variations of passages of LoreIpsum available, but the majority have suffered alteration in some formby injected humour, or randomised words which don't look even slightlbelievable. If you are going to use a passage of Lorem Ipsum, you neeto be sure there isn't anything embarrassing hidden in the middle otext. All the Lorem Ipsum generators on the Internet tend to repeapredefined chunks as necessary, making this the first true generator othe Internet. It uses a dictionary of over 200 Latin words, combinewith a handful of model sentence structures, to generate Lorem Ipsuwhich looks reasonable. The generated Lorem Ipsum is therefore alwayfree from repetition, injected humour, or non-characteristic words etc."`;

function App() {
const [message, setMessage] = useState("");
// Here i'm updating this count to calculate the clicks of the button
const [count, setCount] = useState(0);

useEffect(() => {
if (!words) {
setWords(longText);
setCount((prev) => prev + 1);
}
}, [words]);

return (
<div style={{ padding: 24 }}>
<button
onClick={() => {
setMessage("");
}}
>
Click me!
</button>

<div
id="container"
style={{
color: "black",
background: "yellow",
height: "500px",
padding: 16,
}}
>
<h1>{count}</h1>
{message}
</div>
</div>
);
}

export default App;

This is what you will see on the browser

useEffect

Notice that a glitch happens sometimes when I click the button to update the message? This is due to useEffect not blocking the DOM and allowing the DOM to paint before the updated text managed to render correctly. This causes the glitch effect and a bad user experience.

Let’s see how useLayoutEffect can fix this.

....

useLayoutEffect(() => {
if (!words) {
setWords(longText);
setCount((prev) => prev + 1);
}
}, [words]);

....
useLayoutEffect

And there you have it! No more glitching effects! This is due to the fact that useLayoutEffect runs synchronously internally; causing a temporary block on updates to the DOM, and the DOM will only be rendered after the useLayoutEffect’s effect has been executed.

It is important to also note that the useLayoutEffect will block the browser’s layout and paint until it completes, which can cause a visual delay, so it should be used with caution, conscientiously, and only when necessary.

Final Thoughts

As a best practice, if you’re not sure whether to use useEffect or useLayoutEffect, it’s recommended to start with useEffect and only use useLayoutEffect if you find that there are visual inconsistencies or layout issues. useLayoutEffect may also hurt performance because it blocks the browser’s ability to render updates to the screen until the layout calculation is complete.

--

--

Mohamed Khan
Reflex Media
0 Followers
Writer for

Senior Software Engineer with expertise in front-end development and a passion for web development and new technologies.