As @DoubleAA wrote in the comments, this is not halacha, but a minhag brought by some, e.g., from here #2
- "Ritual immersion on a regular basis (not just because of the decree of Ezra) is fitting for a sofer" (Chida)
- It is fitting to be particular about this matter (Aruch HaShulchan; Kesset HaSofer).
R Reuvain Mendlowitz in his book Inside stam (p.73) writes
A number of sources [cf. above] mention the concept of a sofer immersing in the
mikveh before writing a stam item or a Shem Hashem within one. While different communities follow different customes in this regard,
it would be a hiddur for the sofer to immerse in a mikveh at
least when impure so as to write only in a purified state (as so did I hear from R Mordechai Friedlander).
Note however that a possible mistake is for sofrim of tefilin or mezuza to leave blanks for the name of God so they can write them "in one go" after immersing in a mikve. Since tefilin and mezuzot have to be written k'sidran (in the order of the text, without going back, SA OC 32:1, see e.g., here), this invalidates the parchment. This is a case where mistaken application of a minhag can go against basic halacha.