TARMIYA, Iraq — Islamic State militants dressed in Iraqi military uniforms launched a brazen nighttime attack in a farming hamlet close to Baghdad, killing 21 members of a local tribe that has been a vocal opponent of the extremists, security officials and residents said Wednesday.

The hourlong gun battle late Tuesday in this rural area approximately 25 miles north of the capital threatens growing optimism among both Iraqi officials and the international coalition fighting the Islamic State that Iraqis are gaining momentum in their efforts to stabilize cities and communities devastated by violence.

Although Iraqi forces are still engaged in mopping-up operations to rid pockets of the country of sleeper cells, terrorist attacks and civilian deaths have dropped sharply since the government declared victory over the Islamic State in December. In April, 68 Iraqi civilians were killed in acts of terrorism, violence and armed conflict, according to the United Nations, continuing a steep decline of violence in a country once plagued by almost daily suicide bombings and other terrorist attacks.

But the high death toll on Tuesday — 18 men, two women and a 5-year-old girl — and the timing of the attack are especially worrisome. Iraqi security forces were already on high alert across the nation ahead of national elections scheduled for May 12.