Do local patents have precedence over foreign patents even if the foreign patent was granted first? Let's say that a patent was granted in 2010 after the application was made in the same year, but in the U.S. another company made an application for the same patent in 2020 and was granted the patent in 2021, does the patent in the U.S. have legal precedence in U.S. court over the foreign patent and why?
You may not have a clear understanding of patents. They are 99.9%* territorial. A patent issued by the USPTO is the only patent relevant to the making, selling, offering for sale, importing, or using a patented product in the U.S.
And the same for all other countries. Of course U.S. companies not only file for U.S. patents; they also file for German, Chinese and any other places they see fit and have the funds to pursue. Likewise, Chinese companies file with the USPTO for U.S. patents.
If a filing by by company A in any country occurs before a filing by company B in any country and A's filing makes B's not new, then B should not a patent in whatever place it has filed.
Also, merely getting a patent does not violate someone else's patent, a product can infringe a patent. Actually a product can infringe many patents from many patent owners. And having a patent doesn't automatically allow for the production of a product practicing that patent.
(the 0.1% is for odd corner cases at sea or involving importing of components of patented items)