The best way to avoid thunderstorms is to pay close attention to weather forecasts and sit out storms or hike during the hours when they're less likely to occur.
With a little experience, you can also accurately forecast the weather by keeping a close eye on cloud formations, wind speed, wind direction, or barometric pressure when hiking out in the open where the threat of lightning and hail is the greatest. Try looking at the first image to get an idea of how thunderstorms form, and then you'll be able to recognize the signs a bit more while hiking.
For example, in New England (especially in the White Mountains and along the Vermont, New Hampshire, and Maine sections of the Appalachian Trail) thunderstorm activity is highly seasonal, occurring most frequently from June through August. If you plan on hiking or backpacking in the area during these months, make sure you build a bad weather day or two into your schedule in case you need to abort a hike because of dangerous weather. Local hikers do this all the time, because if an emergency arises where you do need search and rescue help, no one is going to come until the storm is over.
Summer storms usually happen between noon and midnight, when the sun has heated up the moist air. If you're hiking thru exposed areas, make sure to start early so you're past the areas before peak thunderstorm times.
If you're in an open area where you can see the sky, look for activity by searching for large, puffy cumulus clouds. If you see very tall or anvil shaped clouds, expect a story! I've seen these form more than 20 miles off, and been able to get out of open area before the storms hit.
The sight of these clouds encouraged me to hike a lot faster and to get below treeline before they arrived and let loose their full wrath!