We present time-resolved optical photometry of the binary millisecond `redback pulsar PSR J1023+0038 (=AY Sex) during its low-mass X-ray binary phase. The light curves taken between 2014 January and April show an underlying sinusoidal modulation due to the irradiated secondary star and accretion disc. We also observe superimposed rapid flaring on time-scales as short as ~20 s with amplitudes of ~0.1-0.5 mag and additional large flare events on time-scales of ~5-60 min with amplitudes ~0.5-1.0 mag. The power density spectrum of the optical flare light curves is dominated by a red-noise component, typical of aperiodic activity in X-ray binaries. Simultaneous X-ray and UV observations by the Swift satellite reveal strong correlations that are consistent with X-ray reprocessing of the UV light, most likely in the outer regions of the accretion disc. On some nights we also observe sharp-edged, rectangular, flat-bottomed dips randomly distributed in orbital phase, with a median duration of ~250 s and a median ingress/egress time of ~20 s. These rectangular dips are similar to the mode-switching behaviour between disc `active and `passive luminosity states, observed in the X-ray light curves of other redback millisecond pulsars. This is the first time that the optical analogue of the X-ray mode-switching has been observed. The properties of the passive and active state light curves can be explained in terms of clumpy accretion from a trapped inner accretion disc near the corotation radius, resulting in rectangular, flat-bottomed optical and X-ray light curves.