Why does the 2021 Mac have a lower Ghz processor than the 2017?
I take it you are concerned that in some way a lower GHz indicates less powerful CPU.  But let's look in a little detail at the GHz values and the different 'generation' of CPU.  I will just consider the lowest specs, that is

2017: 3.4GHz quad‑core Intel 7th-generation Core i5 (Turbo Boost up to 3.8GHz)
2021: 3.1GHz 6‑core Intel 10th-generation Core i5, Turbo Boost up to 4.5GHz.

Firstly there is 3-generations of Intel's Core processors between the two.  Without attempting to be specific, we can assume some improvement in efficiency for the same speed processor.
For mostly single-threaded applications (e.g. browser, word processor) the Turbo-boost value is important.  Here we see in increase in processor speed from 3.8 to 4.5 GHz.
The processor load will increase as more applications (and background tasks) are running and as the type of application moves to those being multi-threaded which can use many processor cores.  Such applications include photo and video processing.
At maximum load, all 4 cores (2017) or all 6 cores (2021) will become fully utilised.  When fully utilised the processor speed may reduce to 3.4 GHz (2017) and 3.1 GHz (2021). If we multiply cores by GHz (3.4x4 and 3.1x6) we can see that that the newer processor is capable of considerably more work - the lower speed is outweighed by the increase in core count.
In practice both CPUs will probably run a bit faster than 3.4 and 3.1 GHz when under full load unless the ambient temperature is high.
In summary we have three things making the newer CPU outperform the older one:

Newer generation of processor;
Single threaded speed (maximum Turbo Boost);
Core count (even though base speed is lower).

You also might like to know that, as a power saving measure, both processors will reduce their speed when under a light load.
And, of course, there are considerably higher performance CPUs available for both 2017 and 2021 iMacs if that is desired.
Finally you might like to browse Geekbench results for the two processors:

2017
2021

These show a modest improvement in single threaded performance and a greater improvement in multi threaded.