Two-factor authentication (2FA) or two-step verification (2SV) should be used with online accounts whenever possible. After entering a password, both methods require an authentication code to be entered to complete the login process. It is best to get such codes from authentication apps like 1Password, Authy, or Google Authenticator, but many websites still send codes by text message or email—although less secure, they are better than nothing.
If you receive a 2FA code that you did not request, it is likely that someone else is trying to log in to your account and already has your password. But the extra authentication step has done its job and has protected your account from being compromised. A hacker may email or text you with a story about why you should send the code to them, and since authentication codes are short-lived, this would happen right away—but do not share the authentication code with anyone.
Instead, independently from the message with the code, go to the account website, log in, and change your password. As always, make sure the password is strong, unique, and stored in your password manager. And if the nearly-hacked account used a password that was shared with other accounts, you should change the passwords on those accounts as well.
Authentication codes (that you do not request) are most often generated when your email address and password have been stolen, probably in a significant site breach. You can check Have I Been Pwned to see if your account is floating around on the “dark web”; password managers perform similar checks. Changing your password on any site that is breached is essential.
Beyond a data breach, an authentication code could also be generated in instances of identity theft. When someone is trying to create an account to impersonate you, unfortunately there is not much you can do to stop such attempts. But if the account has been created, you should be able to change the password yourself, then either let the account simply sit in your password manager or try to delete it.
Keep in mind that someone could have also just accidentally entered your email address or phone number instead of theirs when trying to make an account. In instances where you are certain you do not have an account at the site in question, and where you only get one authentication code, you are likely safe ignoring the message. But never ignore 2FA codes that you did not request for sites where you have an account. Rather, use the code as impetus to change your password for the site.