The first flag of the United States was adopted in 1777 out of three colors: red, white, and blue. The new country had just declared its independence from Britain, and was made up of 13 new states that used to be British colonies. So, they decided to put 13 red and white stripes on the flag. In the blue area of the flag, called the canton, they placed one white star for each of the 13 states of the union: Delaware, Pennsylvania, New Jersey, Georgia, Connecticut, Massachusetts, Maryland, South Carolina, New Hampshire, Virginia, New York, North Carolina, and Rhode Island.
Eventually, two more states were added to the U.S., so they added two more stripes and, of course two more stars for Vermont and Kentucky—15 stripes and 15 stars. Soon enough, there were five new states: Tennessee, Ohio, Louisiana, Indiana and Mississippi. People started to realize that if they kept adding more stripes, those stripes were going to get ridiculously skinny.
In 1818, the United States passed a new Flag Act law, which would keep the number of stripes at 13 in honor of those first 13 states. However, they would add new stars for the flag for the new states to come in the future.
The next state to enter in the union was Illinois, on December 3, 1818. The new Flag Act declared that once a new state or states enter the union, the flag would not officially get its new stars until the next Independence Day, July 4th, which is still the rule today. Because Illinois became a state on December 3, 1818, a new star was officially added to the flag on July 4, 1819.
Two new states had joined the union in the same one-year period: Alabama and Maine—which split off from the Massachusetts. The flag jumped from 21 stars straight to 23 stars in 1820. As time goes by, the number of states increased steadily. From 1822 to the Civil War in 1861, 11 states joined the Union which made the stars number rise to 34: Missouri, Arkansas, Michigan, Florida, Texas, Iowa, Wisconsin, California, Minnesota, Oregon, and Kansas.
The Unites States kept all the stars even for those states that were trying to leave the union. During the war, a bunch of the western counties of Virginia wanted to stay part of the USA. Therefore, in 1863, Congress let them split from Virginia and become the brand-new state of West Virginia, and the flag had 35 stars. Later, from 1865 to 1912, there were 13 new states: Nevada, Nebraska, Colorado, North Dakota, South Dakota, Montana, Washington, Idaho, Wyoming, Utah, Oklahoma, New Mexico, Arizona—48 stars.
In 1912, the first specific star pattern was made official by the U.S. government. Before that year, people were just making up lots of different star arrangements. The number of stars stayed at 48 for quite a while until 1959, when Alaska and Hawaii became the two last stars of the U.S. flag—with 50 stars that we still have today.
Sources: USA Today, Britannica, Public Broadcasting Service, US history, US Flag, History, National Flag Foundation, Battlefield