Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
Issue storing ref elements in loop

When trying to store refs in an array inside a loop, I get weird results when the page re-renders (everything is as expected when the page first renders).

I reproduced the problem in this very small jsfiddle: https://jsfiddle.net/69z2wepo/68251/

class Hello extends React.Component {
  constructor(props) {
      super(props);

      setTimeout(() => { this.setState({foo: 'bar'}); }, 1000);
  }

  render() {
    console.log('--- RENDER ---');

    const divs = [];
    this.elements = [];

    for (let i = 1; i <= 2; i++) {
        divs.push(
            <div
                key={i}
                ref={(ref) => {
                    this.elements.push(ref);

                    console.log(this.elements);
                }}
            >
            </div>
        );
    }

    return (
        <div>
            {divs}
        </div>
    );
  }
}

ReactDOM.render(
  <Hello />,
  document.getElementById('container')
);

You can see that when the page renders a second time, I suddenly get null values and end up with an array of 4 elements.

Could anyone explain why it behaves like that? Why is the function handling the ref executed 4 times after the second rendering?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

From the documentation:

React supports a special attribute that you can attach to any component. The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.

So the reason why four ref callbacks are called is because two components are unmounted and two are mounted.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda