After school and on weekends, he knocked on hundreds of doors in an attempt to reach every registered Republican in his district, which covers one full county and parts of three others. He won his party’s primary by 45 percentage points in May.

“In the beginning, I knew the odds were against him,” said Andrew Gilson, who taught Mr. Hanna in Advanced Placement government class. Mr. Gilson assumed that his student was running mainly to gain experience for later in his career.

But Mr. Gilson’s opinion changed after Mr. Hanna’s landslide victory in the primary. “Well, maybe he’s got a shot here,” he recalled thinking. “Things were so fickle and fluid at the moment in politics, and even nationally.”

Mr. Hanna then toppled Mr. Lynch in the general election in November, winning by 25 percentage points. “It was kind of a surprise,” Mr. Gilson said, pointing out that the rural district is predominantly older, white and conservative. Voters are mostly focused on the economy, he said, while age and race are marginal issues.