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

65
Views
Splice an array in React keeps rerendering

In the update(changeProps) function, I have something like this:

 update(changedProps) {
      if (this.person) {
        this.__arr = ['hi', 'hi', 'hi'];
      } else {
        this.__arr = ['bye', 'bye', 'bye', 'bye'];
      }

    if (this.__hello) {
      this.__arr.splice(1, 0, 'hello');
    }

    super.update(changedProps);
  }

Say this.person is true, when I click elsewhere and the page rerenders, it becomes

this.__arr = ['hi', 'hello', 'hi', 'hi']

Then when it rerenders again: this.__arr = ['hi', 'hello','hello', 'hi', 'hi']

It keeps adding to the array after each rerender. Same for if this.person is not true. How do I make it so it only adds it once?

If I did something like this: this.__arr = [...this.__arr, 'hello'], it can add it to the end, but I want to add an element to index 1

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Two things:

  1. Don't mutate:
    if (this.__hello) {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
  1. Do you want to do this every time the component updates, or just once?
    if (this.__hello && this.__arr[1] !== 'hello') {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
about 4 years ago · Juan Pablo Isaza 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!