Blog, COLDSURF

useEffect and useLayoutEffect

#react

useEffect

Unlike componentDidMount or componentDidUpdate, the effect used in useEffect does not block the browser from updating the screen. This helps improve the responsiveness of the application.
Most effects do not need to be executed synchronously. In some rare cases, such as measuring layouts, synchronous execution is required, for which there is a separate hook called useLayoutEffect, which uses the same API as useEffect.
To explain this with code:
const Page = () => { const [name, setName] = useState("") useEffect(() => { setName("John Doe") }, []) return <h1>My name is {name}</h1> }
In the above code, the initial value of name is an empty string ("").
The useEffect hook is used to change the name to "John Doe" during the initial render.
If you run this code, you might notice a brief layout shift (flickering effect).
(For this, you can experience the layout shifting by throttling the browser's network settings to slow it down.)
To prevent this, you can use useLayoutEffect instead.

useLayoutEffect

If we use useLayoutEffect instead of useEffect, the code would look like this:
const Page = () => { const [name, setName] = useState("") useLayoutEffect(() => { setName("John Doe") }, []) return <h1>My name is {name}</h1> }
With this code, the text "John Doe" will be rendered on the screen without layout shifting.
  • useLayoutEffect:
    • Executes before the DOM is painted
    • Synchronous execution
  • useEffect:
    • Executes after the DOM is painted
    • Asynchronous execution

Reference

https://merrily-code.tistory.com/46
ā† Go home