To exploit the quantum coherence of electron spins in solids in future technologies such as quantum computing1, 2, it is first vital to overcome the problem of spin decoherence due to their coupling to the noisy environment. Dynamical decoupling3, 4, 5, 6, 7, 8, 9, which uses stroboscopic spin flips to give an average coupling to the environment that is effectively zero, is a particularly promising strategy for combating decoherence because it can be naturally integrated with other desired functionalities, such as quantum gates. Errors are inevitably introduced in each spin flip, so it is desirable to minimize the number of control pulses used to realize dynamical decoupling having a given level of precision. Such optimal dynamical decoupling sequences have recently been explored9, 10, 11, 12. The experimental realization of optimal dynamical decoupling in solid-state systems, however, remains elusive. Here we use pulsed electron paramagnetic resonance to demonstrate experimentally optimal dynamical decoupling for preserving electron spin coherence in irradiated malonic acid crystals at temperatures from 50 K to room temperature. Using a seven-pulse optimal dynamical decoupling sequence, we prolonged the spin coherence time to about 30 s; it would otherwise be about 0.04 s without control or 6.2 s under one-pulse control. By comparing experiments with microscopic theories, we have identified the relevant electron spin decoherence mechanisms in the solid. Optimal dynamical decoupling may be applied to other solid-state systems, such as diamonds with nitrogen-vacancy centres13, 14, 15, and so lay the foundation for quantum coherence control of spins in solids at room temperature.