Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda