Molecular switches enable the fabrication of multifunctional devices in which an electrical output can be modulated by external stimuli. The working mechanism of these devices is often hard to prove, since the molecular switching events are only indirectly confirmed through electrical characterization, without real-space visualization. Here, we show how photochromic molecules self-assembled on graphene and MoS2 generate atomically precise superlattices in which a light-induced structural reorganization enables precise control over local charge carrier density in high-performance devices. By combining different experimental and theoretical approaches, we achieve exquisite control over events taking place from the molecular level to the device scale. Unique device functionalities are demonstrated, including the use of spatially confined light irradiation to define reversible lateral heterojunctions between areas possessing different doping levels. Molecular assembly and light-induced doping are analogous for graphene and MoS2, demonstrating the generality of our approach to optically manipulate the electrical output of multi-responsive hybrid devices.