UseLayoutEffect (Layout Side effects)

Layout side effect

  • useEffectIn the browser.Execute after rendering is complete

  • useLayoutEffectIn the browser.Pre-render execution

Features:

  • Tasks in useLayoutEffect should affect the Layout, otherwise they should not take up time

  • UseLayoutEffect is always executed before useEffect

    Note: useEffect is preferred for the user experience.

Code 1 demo (printed at different times)

import React, {useState, useRef, useLayoutEffect, useEffect} from "react"; import ReactDOM from "react-dom"; function App() { const [n, SetN] = useState(0) const time = useRef(null) const onClick = ()=>{setN(I => I +1) time.current = performance.now()// Time } useLayoutEffect(()=>{console.log(performance. Now () - time.current)}}) return (  <div className="App"> <h1>n: {n}</h1> <button onClick={onClick}>Click</button> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);Copy the code

Code 2 demo (print useLayoutEffect and then print useEffect)

import React, {useState, useLayoutEffect, useEffect} from "react"; import ReactDOM from "react-dom"; function App() { const [n, setN] = useState(0) const onClick = ()=>{ setN(i=>i+1) } useEffect(()=>{ console.log("useEffect") }) UseLayoutEffect (()=>{console.log("useLayoutEffect")}) return (<div className="App"> <h1>n: {n}</h1> <button onClick={onClick}>Click</button> </div> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);Copy the code