So you buy Stock X.
X means "This stock, at this time, at this cost."
If you sell Stock X, you pay taxes on any amount greater than that stock's cost at the time you purchased it.
If Stock X pays a dividend, when it pays the dividend, that is income. You pay taxes on that.
If that income is reinvested into the stock market, the payment to you is still a taxable event. If you then reinvest, you have Stock Y.
Stock X will sell, if you ever sell it, with taxes judged from the cost of that stock when you bought it.
New Stock Y will sell with taxes judged from the new cost of the stock when you bought much later with the dividend reinvestment.
Every dividend event is creating a new stock position when you reinvest, even with the same ticker, and a new taxable event, and all dividends paid will keep doing this. New stock won't be "taxed twice" because your taxable gains are only counting from the price of each new position purchased. You only get capital gains tax on money above that new purchase price on that new quantity of stock.