Hanging valleys were either previously river valleys which hadn’t been glaciated or tributary glacier valleys.
They’re a product of different rates of erosion between the main valley and the tributary valleys. The main glacier will erode more of the glacial trough as it has more energy, due to its mass, and carries more moraine. The tributary glacier will have less moraine and less mass and will therefore have less erosive power.
The valley eroded by the main glacier will be deeper than the tributary valley, meaning the tributary valley floor is much higher than the main glacial trough when the ice retreats.
When rivers return after the ice melts, waterfalls will form in the hanging valley, e.g. – Lady Bowen Waterfall in New Zealand (as shown above).