They do it to avoid danger and save energy. The largest bat colony, in Bracken Cave, Texas, is thought to contain 20 million bats. Some species use caves for daytime roosting; others hibernate there for the winter because caves provide optimal humidity, a stable low temperature, and few disturbances from light or noise.
Temperature is important because bats are warm-blooded but very small. Unlike other mammals, they let their internal temperature drop when they are resting, going into a state of decreased activity to conserve energy. Hibernation is an even deeper state of inactivity in which their body temperature drops to that of the cave.
A special adaptation allows bats to hang upside down for months without using any energy. A tendon from their talons is connected to their upper body, not to a muscle. So when they hang, the weight of their body holds them in place. They can then drop straight into flight when they wake up.