xml ui - layout effect

useLayoutEffect has the very same signature as useEffect.

useLayoutEffect(effectFunction, arrayDependencies)
() => {
    const [randomNumber, setRandomNumber] = useState(0)
    const [effectLogs, setEffectLogs] = useState([])
  
    useLayoutEffect(
      () => {
        setEffectLogs(prevEffectLogs => [...prevEffectLogs, 'effect fn has been invoked'])
      },
      [randomNumber]
    )
  
    return (
      <div>
        <h1>{randomNumber}</h1>
        <button
          onClick={() => {
            setRandomNumber(Math.random())
          }}
        >
          Generate random number!
        </button>
        <div>
          {effectLogs.map((effect, index) => (
            <div key={index}>{'🍔'.repeat(index) + effect}</div>
          ))}
        </div>
      </div>
    )
  }

useLayoutEffect vs useEffect

The function passed to useEffect fires after layout and paint. i.e after the render has been committed to the screen.

This is okay for most side effects that should NOT block the browser from updating the screen.

There are cases where you may not want the behaviour useEffect provides. e.g. if you need to make a visual change to the DOM as a side effect. To prevent the user from seeing flickers of changes, you may use useLayoutEffect.

The function passed to useLayoutEffect will be run before the browser updates the screen.

https://react-hooks-cheatsheet.com/

posted @ 2020-10-26 13:13  fndefbwefsowpvqfx  阅读(53)  评论(0编辑  收藏  举报