I'm trying to merge two lists.
1st way I get an alert that the list is merged (in the useEffect hook) but in the second condition, I don't get the alert, the useEffect dependent on state does not work. So would like to know the reason. Am I doing something wrong?
First way -
export default function Test() {
const [firstList, setFirstList] = useState([{ a: "2" }, { b: "3" }]);
const [secondList, setSecondList] = useState([{ c: "4" }, { d: "5" }]);
useEffect(() => {
alert(JSON.stringify(firstList) + " list is merged");
},[firstList]);
function mergeList() {
secondList.forEach((d) => setFirstList((firstList) => [...firstList, d]));
}
return <button onClick={mergeList}>Click</button>;
}
Second way - if I write my mergeList function this way.
function mergeList() {
let previous = firstList;
secondList.forEach((d) => previous.push(d));
setFirstList(previous);
}
This Why can't I directly modify a component's state, really? shows we can do state change this way, but I'm not able to follow.