system
Given the following post, respond as if you're commenting on Reddit:
human
ELI5: Why did infantry soldiers make a square formation against cavalry?

I have seen several photos of soldiers in the Napoleonic era forming square against cavalry charges. What benefits did this yield, and was it an effective strategy?

Edit: Thanks for the excellent responses, guys!
gpt
A well disciplined square formation was absolutely very effective against cavalry (although by no means immune) but only if done right. 

First, there's no flank or rear to attack, which is the ideal tactic when using cavalry. In a square formation, all your weapons are facing outward.

Second, horses have the same self preservation instinct as humans but without military training, and and such, they won't willing run into volley fire or a wall of bayonets. A well timed square could catch a cavalry charge off guard and take large numbers of them out with volley fire and impale the rest with bayonets.

The flip side is that a poorly timed or executed square could quickly turn into a death trap. If the square formed too early or didn't time their fire correctly, the cavalry could regroup at a safe distance and harass them back with their own fire. Worse, infantry support could surround the square and attack or hold them in place under artillery fire.