Hair dyes can be simple coloring agents, such as henna, that simply add a dye or pigment to the hair, or they can be complicated chemical reactions that open up the hair shaft, bleach the hair to a lighter color, and then react with the hair to form a permanent bond that colors the hair the desired shade.
It is not easy to make a dye stay stuck to hair. This is a good thing if you want to dye your hair blue for Halloween. Temporary dyes usually have large molecules that cannot penetrate into the hair shaft. They will wash out easily with shampoo. Since they contain no bleaches or ammonia, they are gentle on hair.
If you want to cover gray or darken light hair, slightly more permanent dyes that will last a number of washings are available. Some use no alkaline developers to open up the hair to absorb the dye, and so they rely on the small size of the dye molecules to help penetrate into the hair. They will last through 4 to 5 shampooings.
For a little more permanence (20 or more shampooings), a gentle alkali like sodium carbonate and a low strength solution of hydrogen peroxide can open up the hair and chemically bind the dye to the hair. Since the low strength of the peroxide does not bleach the hair, the resulting dye looks more natural, as the variations in the hair still show through.
For the most permanent dye, one that will not wash out, ammonia and strong hydrogen peroxide are used. The peroxide bleaches the hair, so that dark hair can be dyed a lighter color. But the main reason for using the peroxide is because the dye is actually formed from small molecules that bind to the hair and then react with the ammonia and peroxide to form larger molecules that are locked into the hair strand.