The same reason that the day isn’t hottest at noon or coolest at midnight.
The Earth has a huge thermal mass. It takes a lot of energy to heat it up and it releases a huge amount of heat as it cools down.
The Sun is hottest at noon, but still hot after that, until it sets. That means that 3 or 4PM is the hottest part of the day, the heat that arrived after noon continues to warm the planet. Similarly, the Earth cools as long as there isn’t sunlight where you are measuring, so the night is coldest just before sunrise.
It’s about gain versus loss. In December you are losing more heat than you are gaining. In June you are gaining more heat than you are losing. But in July, even after the days are getting shorter, they are still longer than the nights. You are still gaining heat. Think of it like a bathtub. If you drain water at 1 gallon a minute, the tub will fill at an intake of any number higher than that. At the peak of 2 gallons a minute intake the water level goes up, but when you turn the water intake down to 1 and 1/2 gallons a minute, your tub is still filling. Only after you go below 1 gallon a minute intake does the tub start to drain. It continues to fill after the maximum and only starts to drain when the fill rate is less than the drain rate.
Imagine the temperature is like the water level in a leaky bucket, and the heat from the sun is you filling that bucket. You fill it slower in the winter, faster in the spring, fastest on the summer solstice, and then slow back down as you go through summer and into fall.
But the fill level of the bucket isn’t maxed out when you’re adding at the fastest — as long as you’re filling it faster than it’s leaking out, you’re still adding more water to it. It’s not until you’re filling up the bucket *slower* than it’s leaking that it will actually drop in water level.
The local temperature works largely the same way. A lot more heat energy is being added than is being shed during the summer solstice, but even weeks after, there’s still more gain than shed (on average), so it continues to get hotter. Only once you start shedding temperature faster than you’re gaining it will the temperature start to go down.
It’s called “seasonal lag.”
Essentially, water absorbs heat in the summer and then releases it in the winter. A similar phenomena (not necessarily water) can be seen on several other planets but perhaps most pronounced on Uranus which is basically tilted on its side, making the difference between summer and winter more severe.
The lag also varies by area, specifically those surrounded by water experiencing a longer lag. Ask any San Franciscan and they’ll tell you September and October are the warmest months, not June.
Latest Answers