# react-useLayoutEffect

2 min read
Table of Contents

主要作用

核心特点

注意事项

总结

我们可以使用useLayoutEffect来处理DOM操作

import React, { useLayoutEffect, useEffect, useRef } from 'react'
export default function App() {
const scrollHandler = (e: React.UIEvent<HTMLDivElement>) => {
const scrollTop = e.currentTarget.scrollTop
window.history.replaceState({}, '', `?top=${scrollTop}`)
}
const container = useRef<HTMLDivElement>(null)
useLayoutEffect(() => {
if (container.current) {
const top = window.location.search.split('=')[1]
container.current.scrollTop = Number(top) || 0
}
})
return (
<div
onScroll={scrollHandler}
ref={container}
id="container"
className="h-[500px] overflow-auto"
>
{Array.from({ length: 500 }).map((_, index) => {
return <div key={index}>{index + 1}</div>
})}
</div>
)
}
My avatar

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.


More Posts

Comments