const everywhere
In most cases you should be able to just use const for all variables so avoid using let
arr state
We should not be maintaining state outside of react components in global like variables like this:
First off we will start by managing arr
in react component state, so start by uncommenting line 17
// const [arr, setArr] = useState([0]);
initializing arr
function initarr() {
// setArr([]);
arr = [];
while (arr.length < sizeValue) {
var r = Math.floor(Math.random() * 100) + 50;
if (arr.indexOf(r) === -1) arr.push(r);
}
initTowers();
}
useEffect(() => {
initarr();
}, [sizeValue]);
Move the code of initArr
function inside useEffect
and then instead of calling initTowers
use setArr
. Example:
useEffect(() => {
const newArr = []; // declare new const arr and not mutate existing variables
while (newArr.length < sizeValue) {
// code
}
setArr(newArr);
}, [sizeValue]);
Send setArr
to sorting functions instead of initTowers
Instead of sorting algorithms calling initTowers
function let them set the updated arr using setArr
bubbleSort(arr, initTowers);
// change to
bubbleSort(arr, setArr);
Move the logic of initTowers
into a useEffect to reset towers whenever arr
changes
function initTowers() {
let temptowers: JSX.Element[] = arr.map((n: number, index: number) => (
<div
className={"bg-black tower"}
key={index}
style={{ height: `${n / 7}rem` }}
></div>
));
setTowers(temptowers);
}
becomes
useEffect(() => {
const temptowers: JSX.Element[] = arr.map((n: number, index: number) => (
<div
className={"bg-black tower"}
key={index}
style={{ height: `${n / 7}rem` }}
></div>
));
setTowers(temptowers);
}, [arr, temptowers]);
This will ensure that the towers always update when arr
changes