Avoid Flashes of Content in React with useLayoutEffect

Share this video with your friends

Send Tweet

At first glance, the useLayoutEffect and useEffect hooks look the same because they have a very similar function signature. There is, however, a subtle but important difference between them: the timing of when they get executed.

While useEffect runs after the DOM paints to avoid blocking the page load, useLayoutEffect runs before the DOM paints, which can help avoid issues with positioning or styling. Generally speaking, you want to use the useLayoutEffect instead of useEffect when you are interacting with the DOM directly.

Like useEffect, useLayoutEffect takes two arguments: a function and an optional dependency array.

useLayoutEffect(() => {
	// Runs every time the component renders
}, [])

useLayoutEffect(() => {
	// Runs only on initial render
}, []) // Optional second argument: dependency array

useLayoutEffect(() => {
	// Runs only when 'apiData' changes
}, [apiData])
Alex
Alex
~ 3 years ago

Heads up, I think your first useLayoutEffect hook in the above code block should omit the dependency array [] in order to be loaded on every render.