Piezoelectric response and optical switch of polarization in BaTiO3 and ferroelectric HfO2