useLayoutEffect
is almost the same as useEffect
except that it's synchronous to render as opposed to scheduled like useEffect
is. If you're migrating from a class component to a hooks-using function component, this can be helpful too because useLayoutEffect
runs at the same time as componentDidMount
and componentDidUpdate
whereas useEffect
is scheduled after. This should be a temporary fix.
The only time you should be using useLayoutEffect
is to measure DOM nodes for things like animations. In the example, I measure the textarea after every time you click on it (the onClick is to force a re-render.) This means you're running render twice but it's also necessary to be able to capture the correct measurments.
If you make the useLayoutEffect
into a useEffect
it will have a janky re-render where it'll flash before it renders correctly. This is exactly why we need useLayoutEffect
.
<iframe src="https://stackblitz.com/edit/ir5-ddxufe?embed=1&file=src/routes/UseLayoutEffect.jsx" style="width: 100%; height: 500px"> </iframe>
标签:render,measure,React,re,time,useEffect,useLayoutEffect From: https://www.cnblogs.com/Answer1215/p/16970096.html