Context. Water together with O2 are important gas phase ingredients to cool dense gas in order to form stars. On dust grains, H2 O is an important constituent of the icy mantle in which a complex chemistry is taking place, as revealed by hot core observations. The formation of water can occur on dust grain surfaces, and can impact gas phase composition. Aims. The formation of molecules such as OH, H2 O, HO2, H2 O2, as well as their deuterated forms and O2 and O3 is studied in order to assess how the chemistry varies in different astrophysical environments, and how the gas phase is affected by grain surface chemistry. Methods. We use Monte Carlo simulations to follow the formation of molecules on bare grains as well as the fraction of molecules released into the gas phase. We consider a surface reaction network, based on gas phase reactions, as well as UV photo-dissociation of the chemical species. Results. We show that grain surface chemistry has a strong impact on gas phase chemistry, and that this chemistry is very different for different dust grain temperatures. Low temperatures favor hydrogenation, while higher temperatures favor oxygenation. Also, UV photons dissociate the molecules on the surface, that can reform subsequently. The formation-destruction cycle increases the amount of species released into the gas phase. We also determine the time scales to form ices in diffuse and dense clouds, and show that ices are formed only in shielded environments, as supported by observations.