Minecraft wiki entry for Spawn, associated text: A mob that has had no player within 32 blocks of it for more than 30 seconds, or 10 seconds if in low light levels, has a 1⁄800 chance of despawning on each game tick (1⁄20 of a second), which is a 2.5% chance per second. Therefore, the average lifetime of monsters not within 32 blocks of a player is 40 seconds (after the initial 30 seconds have elapsed).
Mobs other than fish despawn immediately if no player is within 128 blocks of it, while fish despawn if no player is within 64 blocks.[6]
This is a Euclidean sphere, not a cylinder from map top to bottom and not a taxicab sphere (an octahedron). Example: A mob at 0/y/0 remains at least 10 seconds (as above) if the player moves to 65/y/65 (real distance 91.9), but despawns immediately if the player moves to 91/y/91 (real distance 128.7).
The chunk the mob is in must still be loaded for the mob to despawn. Otherwise, the mob is saved until the chunk is loaded again. For example, if a player enters a nether portal while being chased by a spider, the spider is saved, and it resumes chasing the player coming back through the same portal. In the case of a player reloading chunks, the loading happens before the player is added, meaning they may despawn.
Ocelots and most monster mobs (including those that are holding items) despawn if the difficulty is set to Peaceful, regardless of where the player is located. Monster mobs that do not despawn include hoglins, piglins, and shulkers in all editions, as well as vindicators, zoglins, piglin brutes, and evokers in Bedrock Edition.
For despawning to occur, there must be at least one non-spectator player in the dimension.
Chickens that originally spawned as chicken jockeys follow zombie despawn rules, rather than chicken despawn rules.
Wandering traders and trader llamas despawn after 40-60 minutes (2-3 in game days). They also despawn sooner if all the trades are locked.
Endermites despawn after 2 minutes unless named with a name tag or have persistent tag.