In this article I will tell you how to get shorter relay switching times and how to minimize relay current consumption. The same exact things apply to solenoids and solenoid valves.
You need to use a transistor because either relay you want to control needs a higher voltage than your microcontroller can provide, or relay’s current demand is too high. Although some microcontrollers can give enough current to switch a relay, but most of them is incapable of doing that.
And the diode in parallel with relay coil (or solenoid coil) is needed to suppress the flyback voltage that occurs when transistor is switching-off and magnetic field stored in coil collapses. That flyback voltage can reach hundreds of volts, which can completely destroy the driving transistor.
Using Relays (Tips & Tricks) - [Link]