Everything in the universe moves toward greater stability.
Heat moves from a high level of temperature to a low level of temperature. Matter moves from higher level of order to lower level of order or greater entropy.
If atoms can achieve greater stability by sharing electron density they will.
in Water both Oxygen and Hydrogen gain stability by sharing electron density. Oxygen shares the electron density from its two unpaired p orbital electrons. Two Hydrogen share the one unpaired s electron orbital with one of the p orbitals of Oxygen. This leaves Oxygen with 8 electrons in the outer valance shell the same as Neon a very stable inert gas. While Hydrogen achieves the same stable structure as Helium.
In Carbon Dioxide the carbon hybridizes so it can share four of its electrons, with four electrons with another atom. By sharing the electron density of eight electrons Carbon can achieve the electron structure of Neon one of the most stable atoms on the periodic table.