Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
React, How to get computed size, style value in useLayoutEffect?

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.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!