Reinvested dividends are taxed when earned and then add to your cost basis in the investment for capital gains purposes.
For example, you invested $1,000 in a mutual fund and have earned and reinvested $50 in dividends. As a result, your cost basis is $1,050. If you sell all of your fund shares for $1,110, your taxable capital gain would be $60, not the $110 difference between what you originally paid for the fund shares and your selling value. You need to keep track of every share.
Please find additional information here. https://finance.zacks.com/pay-capital-gains-tax-only-sell-reinvested-dividends-2449.html