Look at the noble gases: neon has 8 electrons in its outer shell, argon has 8, and both almost never react. The elements next to them do react, and in ways that land them on the same count. Sodium (2, 8, 1) loses its single outer electron and is left with neon's 2, 8. Chlorine (2, 8, 7) gains one and reaches argon's 2, 8, 8. Atoms in the middle, like carbon with 4, share electrons instead of trading them, since gaining or losing 4 would cost too much energy.
In a shared bond, both atoms count the shared pair. In water, oxygen starts with 6 valence electrons. It forms 2 bonds and keeps 2 lone pairs, so it counts 2×2+2×2=8. Each hydrogen counts only its one bond, 2 electrons, and that fills its first shell, which holds just 2. This 2-electron target for hydrogen is called the duet rule.
The octet rule is a strong tendency, not a law. Boron in BF3 is stable with only 6 electrons around it. Nitrogen monoxide, NO, has 11 valence electrons, an odd number, so one atom must be left with fewer than 8. Atoms from period 3 down, such as phosphorus and sulfur, are large enough to hold more than 8: PCl5 has 10 around phosphorus and SF6 has 12 around sulfur. The rule works best for carbon, nitrogen, oxygen and fluorine, the atoms of most everyday molecules.
Think of it like this. Picture each atom's outer shell as an eight-seat van. An atom with 7 passengers picks up one more, an atom with 1 drops its passenger off with a neighbor, and a full van, like neon's, goes nowhere. The picture leaks at the edges: hydrogen's van has only 2 seats, and large atoms like sulfur can squeeze in extra passengers.
Core idea. Main-group atoms tend to lose, gain or share electrons until their outer shell holds 8, the arrangement of a noble gas; that target predicts ion charges, bond counts and formulas, with known exceptions.