How to prevent React component jumping to original position on re-render using framer motion?

I am new to React development and am currently trying to create a simple web application that visualises the sorting of an array using selection sort. I have App.tsx, and 2 custom components called ArrayComponent.tsx and ArrayBlock.tsx. The current logic I have is the following:

I use a state to store the current locations of each component, where this state is an array of integers. Each array block is assigned an initial ID which is used to index this locations array state. For example, if the first block in the array is initially the number 6, that component will have an id of 0 and locations[0] = 0. If that block is moved to position 2 in the array, then id remains 0, but locations[0] = 2. A state called movers is used with useEffect to trigger the check to see if animation needs to take place, this useEffect is in ArrayBlock.tsx.

The code works fine until a position is swapped more than twice. So if 0 and 2 get swapped, and the block in position 0 is swapped again later, then the block that was moved to position 2 jumps back to its original position at 0 and undergoes the swap instead of what is there currently, which is the block previously in position 2!

I suspect that it has something to do with the way I return the arrayBlock components within ArrayComponent but I can’t seem to crack it – I’ve only really been working with react for about 15 hours at this point.

Here are the main .tsx files:

App.tsx:

import React from 'react';
import './App.css';
import ArrayComponent from './ArrayComponent';
import { useState } from 'react';

const App: React.FC = () => {
  const [valueArr, setValueArr] = useState<number[]>([6, 5, 0, 1, 8, 10, 9, 4]);
  const [movers, setMovers] = useState<[number, number]>([-1,-1]);
  let valueArrCopy = [...valueArr];
  type motionPair = [number, number];
  const movements: motionPair[] = [];
  const updateArr = (i:number, j:number) => {
    setValueArr((prevValues) => {
      const newValues = [...prevValues];
      [newValues[i], newValues[j]] = [newValues[j], newValues[i]];
      console.log(newValues)
      return newValues;
    });
  }
  const updateCopiedArr = (i: number, j:number) => {
    [valueArrCopy[i], valueArrCopy[j]] = [valueArrCopy[j], valueArrCopy[i]];
  }
  const sortArr = async () => {
    let n = valueArr.length;
    console.log("SortArr called");
    for (let i = 0; i < n; i++) {
      let minIndex = i;
      for (let j = i + 1; j < n; j++) {
          if (valueArrCopy[j] < valueArrCopy[minIndex]) {
              minIndex = j;
          }
      }
      if (minIndex !== i) {
        updateCopiedArr(minIndex, i);
        console.log("updated array is: "+valueArrCopy)
        movements.push([minIndex, i]);
      }
    }
    console.log("This is the list of moves: "+movements)
    //Now its time to update the movers array every 6 seconds.
    for (let k = 0; k< movements.length;k++){
      setMovers(movements[k]);
      await new Promise((resolve) => setTimeout(resolve,6000));
    }
  }
  return (
    <div className="capsule">
      <ArrayComponent updateArr = {sortArr} count={valueArr.length} valueArr={valueArr} movers={movers}></ArrayComponent>
    </div>
  );
}

export default App;

ArrayComponent.tsx:

import { useEffect, useState } from 'react';
import './App.css';
import ArrayBlock from './ArrayBlock.tsx';

interface ArrayCompProp{
    count: number;
    valueArr: number[];
    updateArr: () => Promise<void>;
    movers: [number,number];
}

function ArrayComponent({count, valueArr, updateArr, movers}: ArrayCompProp){
  const [locationArr, setLocationArr] = useState<number[]>([0,1,2,3,4,5,6,7]);

  const updateLocation = (id:number, newLoc:number) =>{
    setLocationArr((prevValues) => {
      const newValues = [...prevValues];
      newValues[id] = newLoc;
      console.log(newValues)
      return newValues;
    });
  };

  return (
    <div className="array-container">
      {valueArr.map((value, index) => {
        console.log("This is a rerender: "+value+" and this guy has location of "+locationArr[index]);
        return (
          <ArrayBlock
            key={index}
            id={index} // Assign id in increasing order starting from 0
            location = {locationArr[index]}
            updateLocationArr = {updateLocation}
            value={value} // Ensure the value is correctly accessed
            movers={movers}
          />
        );
      })}
      <button onClick={updateArr}>Perform Sort</button>
    </div>
  );
}

export default ArrayComponent

ArrayBlock.tsx:

import { useEffect, useState } from 'react';
import './App.css';
import ArrayBlock from './ArrayBlock.tsx';

interface ArrayCompProp{
    count: number;
    valueArr: number[];
    updateArr: () => Promise<void>;
    movers: [number,number];
}

function ArrayComponent({count, valueArr, updateArr, movers}: ArrayCompProp){
  const [locationArr, setLocationArr] = useState<number[]>([0,1,2,3,4,5,6,7]);

  const updateLocation = (id:number, newLoc:number) =>{
    setLocationArr((prevValues) => {
      const newValues = [...prevValues];
      newValues[id] = newLoc;
      console.log(newValues)
      return newValues;
    });
  };

  return (
    <div className="array-container">
      {valueArr.map((value, index) => {
        console.log("This is a rerender: "+value+" and this guy has location of "+locationArr[index]);
        return (
          <ArrayBlock
            key={index}
            id={index} // Assign id in increasing order starting from 0
            location = {locationArr[index]}
            updateLocationArr = {updateLocation}
            value={value} // Ensure the value is correctly accessed
            movers={movers}
          />
        );
      })}
      <button onClick={updateArr}>Perform Sort</button>
    </div>
  );
}

export default ArrayComponent

What is written above sums up my latest attempts at fixing the problem. All my previous solutions led to the current solution above. The animation works so long that a single position is not swapped more than once, so for example, an array [5,4,3,2,1] visualises selection sort nicely since the swaps are (0,4) and (1,3). Even with the code above, the longer it runs the more the visualisation goes whacko and blocks fly all over the place, in the wrong places.

I am new to posting on stackoverflow so if I need to provide more information please let me know !!

New contributor

Gregory Maselle is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật