We investigate the baryon fraction in dark matter haloes formed in non-radiative gas-dynamical simulations of the Λ cold dark matter (CDM) cosmogony. By combining a realization of the Millennium Simulation with a simulation of a smaller volume focusing on dwarf haloes, our study spans five decades in halo mass, from 1010 to 1015 h−1 M⊙. We find that the baryon fraction within the halo virial radius is typically 90 per cent of the cosmic mean, with a rms scatter of 6 per cent, independently of redshift and of halo mass down to the smallest resolved haloes. Our results show that, contrary to the proposal of Mo et al., pre-virialization gravitational heating is unable to prevent the collapse of gas within galactic and protogalactic haloes, and confirm the need for non-gravitational feedback in order to reduce the efficiency of gas cooling and star formation in dwarf galaxy haloes. Simulations including a simple photoheating model (where a gas temperature floor of Tfloor= 2 x 104 K is imposed from z= 11) confirm earlier suggestions that photoheating can only prevent the collapse of baryons in systems with virial temperatures T200≲ 2.2 Tfloor≈ 4.4 x 104 K (corresponding to a virial mass of M200∼ 1010 h−1 M⊙ and a circular velocity of V200∼ 35 km s−1). Photoheating may thus help regulate the formation of dwarf spheroidals and other galaxies at the extreme faint end of the luminosity function, but it cannot, on its own, reconcile the abundance of sub-L★ galaxies with the vast number of dwarf haloes expected in the ΛCDM cosmogony. The lack of evolution or mass dependence seen in the baryon fraction augurs well for X-ray cluster studies that assume a universal and non-evolving baryon fraction to place constraints on cosmological parameters.