china – US citizen, traveling to Shanghai with Taiwan layover then a trip to Taiwan NOT for a layover. Do I need a visa?

I will be traveling to Shanghai for 4 days from NYC through Taipei. My layover is long, about 9 hours. I will be traveling back to Taipei but this time I won’t be on a layover, but rather will travel back to NYC after a week in Taiwan.

My original plan was with a layover through Chicago then direct to Shanhai, but the departure from NYC was bad, and the best I can find is through Taipei.

Will I be able to do visa-free transit, or will my layover in Taipei and then return to Taipei require me to apply for a tourist visa to visit Shanghai?

Many thanks.