You should consider three point below:
- You should use
useState hook.
So Use
const [arr, setArr] = useState([]);
Not
const arr = []
When you use React you must consider useState because when you update any variable using useState Hook then React will update the state and can be able to rerender your component. Otherwise, your component will not be updated.
- You should not push directly into the array
arr.
So Use
setArr(item => [...item, newItem])
Not
arr.push('test')
As I explain it above, if you dont use setArr then React will not update your component.
- You should use key when you use multiple html element using map function.
So Use
{arr.map((a, i) => (
<span key={i}>{a}</span>
))}
Not
arr.map((i) => <span>{i}</span>)
Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity.
Here is the complete example:
import { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [arr, setArr] = useState([]);
useEffect(() => {
let newItem = 'test';
setArr(item => [...item, newItem]); // Here we are using `spread operator` to use previous items from `arr`
console.log(arr);
}, []);
return (
<div className="App">
{arr.map((a, i) => (
<span key={i}>{a}</span>
))}
</div>
);
}