Originally, before paint on browser, I know so can't get a computed style data (ex. height, left, width value). but React useLayoutEffect's callback can access and get computed styling data. (It is still invisible(not drawing) in display)
How can I code vanila javascript like useLayoutEffect?
function App() {
const testRef = React.useRef<null | HTMLDivElement>(null);
React.useLayoutEffect(() => {
console.log(testRef.current?.offsetWidth);
}, []);
return (
<AppWrapper>
<div className="test-wrapper" ref={testRef}></div>
</AppWrapper>
);
}
const AppWrapper = styled.div`
max-width: 768px;
margin: 0 auto;
.test-wrapper {
width: 100px;
height: 100px;
background-color: blue;
}
`;
React useLayout before render( showing in display ), get a computed size of dom.
<style>
#test-box {
position: absolute;
left: 100px;
top: 100px;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
<body>
<!-- <div id="test-box"></div> -->
<script>
const textBox = document.createElement('div');
textBox.id = 'test-box';
// print 0
console.log(textbox.offsetWidth);
document.body.appendChild(textBox);
// print 100
console.log(textBox.offsetWidth);
</script>
Vanilla code can't get a computed size before paint.
*** Self Comment ***
First render return + layoutEffect callback is sync logic and then useEffect callback is executed async.
Later, I will find a react's core sync, async execution logic.