How can he be both 22 and 42 when he became king?
He became king at age 22 in the 42nd year of the dynasty, after his father was deemed unfit to rule in the 40th year.
Look carefully at 2 Chronicles 22:1 (the verse before) which explains why the context is different. In 2nd Chronicles it states that the people elected him King in his father's stead, because he was unfit to rule. It also states he “reigned”. It is not fitting here to say that he “became king” – he was chosen as a fit successor before the death of his father, and could not be crowned king until later. That is why in the very next verse it says he became king at 42. See for yourself: 2 Kings 8:16 states he became king at age 32 and ruled for 8 years. His father died in year 40 and Ahaziah was finally crowned king at year 42, and his father was buried as a commoner. (Year –> “Ahaziah was forty-two years old when he became king, and he reigned in Jerusalem one year; his mother’s name was Athaliah daughter of Omri.” see Dr. Jones below for an explanation of this wording.
A fuller answer is given by the sages Rashi and Radak. Radak states,
So what happened was, Joram became sick, so his son ruled as king, but could not be crowned king officially while his father still lived. The people of Jerusalem made Ahaziah king during his father's lifetime since he was smitten with severe illness. If this is not enough, please listen to Dr. Floyd Jones
(To understand this you must look at the surrounding context. One,) The Torah never actually wrote that Jehoram died at 40, just that he ruled for 8 years beginning at the age of 32. Regarding his burial, it says that he was not treated as royalty at his burial – after succumbing to his terrible stomach ailment. Therefore there must have been a period of time between when he became unfit to rule, and was no longer regarded as king. During this time, he became deposed and his son began functioning as prince regent during his lifetime. He was buried as a commoner later on, at the time of his actual death.
Further evidence for this may be found in the fact that II Chronicles 22:1 states that the inhabitants of Jerusalem proclaimed Ahaziah king in his father’s stead.
So, in II Kings 8:26, Jehoram began ruling at 22 – when his father was deposed at the age of 40. His father, however, lingered on in his suffering for another 20 years, and so Jehoram formally became king only at the age of 42.
Thus the sense of Ahaziah’s being “a son of 42 years” in his reigning is seen to refer to his being a son of the dynasty of Omri which was in its 42nd year. Putting the two Scriptures together reveals that Ahaziah was 22 years old when he began to reign during the 42nd year of the dynasty of Omri, of which he is also an integral part.3 [emphasis in original]–Dr. Floyd Jones,
“Chronology of the Old Testament”
Dr. John Gill agrees with this and also supports Rashi's answer:
Dr. John Gill