Why is the difference between useMutationEffect and useLayoutEffect so obscure? What"s the difference?
do your own experiment `console.log ("use" on the start code) / / 1
useEffect(() => {//6
const btn = document.getElementById("btn")
console.log(btn, btn.style.backgroundColor, btn.style.width, btn.style.color, "useEffect")
})
//56view
useLayoutEffect(() => {//5
const btn = document.getElementById("btn")
console.log(btn, btn.style.backgroundColor, btn.style.width, btn.style.color, "useLayoutEffect")
})
useMutationEffect(() => {//4
const btn = document.getElementById("btn")
console.log(btn, btn.style.backgroundColor, btn.style.width, btn.style.color, "useMutationEffect")
})
console.log("use")//2
return (
<div>
{computed}
<input type = "text" value = { value } onChange = {(e) => setValue(e.target.value)} />
<br />
<input type = "text" value = { name} onChange = {(e) => setName(e.target.value)}/>
<Button onClick = { handleClick } style = {{ backgroundColor: "red", width: "50px", color: color}} id = "btn"/>
{console.log("render")}{/* //3 */}
</div>
)
}`
it is found that there is no obvious difference except for the order. It seems that a lot of documents describe it this way:
useMutationEffect
api is the same as useEffect, but before updating the sibling component, it is triggered by Synchronize at the same stage that React performs its DOM changes. Use it to perform custom DOM changes.
useLayoutEffect
api is the same as useEffect, but Synchronize triggers after all DOM changes. Use it to read the layout from DOM and re-render it with Synchronize. Synchronize will be refreshed with planned updates within useLayoutEffect before the browser has a chance to draw.
then comes this sentence:
be careful not to read DOM in useMutationEffect. UseLayoutEffect is more appropriate when reading calculation style or layout information.
then this article: https://stackoverflow.com/que.; Is there any easy-to-understand explanation? Or is it intuitive proof with code?