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

112
Views
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 answers
Answer question

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 Report
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!