What causes the sugar to turn grainy after I have cooked it for a glaze or cooking it with butter for carmelizing?
It sounds like your syrups are crystallizing on you.

For a smooth glaze or caramel, you want tiny little sugar crystals. When you heat your sugar and water mixture, after a certain temperature the water becomes super-saturated with the sugar.

After this super-saturation point, things get dicey. If the solution is disturbed--say by stirring, or an undissolved sugar crystal or other foreign particle getting into the solution--the sugar can rapidly come out of solution and form big crystals. This could be why your confections are grainy.

There are a lot of resources online that have the science behind it and suggestions on preventing it (example, example, example). To summarize a few:


Always use a clean pot or pan.
Make sure the sugar is completely dissolved before it comes to a boil
Dip a pastry brush in water to wash away any sugar that sticks to the side of the pot or pan as the sugar heats.
Combine the sugar with a little water (it should have the consistency of wet sand) before cooking.
Avoid stirring the sugar when it comes to a simmer.
Cover the pan loosely with a lid or baking sheet.
Add a little acid (such as a touch of lemon juice) or corn syrup to the sugar-water mixture before cooking