I am pushing a new item to the array. when a function call."
const tagItem=[];
function handleSelectOption(title, item) {
setCompareTagTitle(title);
tagItem.push(item);
console.log(tagItem)
if (title !== compareTagTitle) {
setCounter(++counter);
} else if (title === compareTagTitle) {
setCounter(counter);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
when the function call at first time it pushes an item in the array, but when the function calls the second time it looks like it overwrites the item and pushes the new item correctly after that.
This is the photo:
The expected result is:
['c++','php', 'java', 'JavaScript']
But it gives me:
['php', 'java', 'JavaScript']

tagItemjust a variable declared at the top level of the component? if so it will be redeclared on each render. If you need it to preserve it's value through renders use arefor a state. (alsopushappends items to the end of the array, your expected value seems to indicate appending to the start)[<>]toolbar button). Stack Snippets support React, including JSX; here's how to do one. (I doubt Next.js is a factor here.)handleSelectOptioncalled? is it called insideuseEffect?