It's a victory for Democratic officials who lead the state and city and have traded insults with US President Donald Trump about his drive to put troops on the ground in major urban areas.
The lawsuit was filed on Monday by Chicago and Illinois to stop the deployments of Illinois and Texas Guard members.
Some troops were already at an immigration building in the Chicago suburb of Broadview when Perry heard arguments on Thursday local time.
The building has been the site of occasional clashes between protesters and agents.
US District Judge April Perry said the actions of the Department of Homeland Security (DHS) are largely rooted in President Donald Trump's "animus toward Illinois elected officials".
She expressed scepticism of the federal government's characterisation of protests in Broadview.
"DHS's narrative of events is simply unreliable," she said.
The city and state have called the deployments unnecessary and illegal, and Illinois Governor JB Pritzker and local officials have strongly opposed the use of the Guard.
In a court filing, the city and state said protests at the temporary detention facility for US Immigration and Customs Enforcement in Broadview have "never come close to stopping federal immigration enforcement".
Trump, meanwhile, has portrayed Chicago as a lawless "hellhole" of crime despite statistics that show a significant drop in crime in the city.
US Justice Department lawyer Eric Hamilton said in court the Guard's mission would be protecting federal properties and government law enforcers in the field — not "solving all of crime in Chicago".
The nearly 150-year-old Posse Comitatus Act limits the military's role in enforcing domestic laws.
However, Trump has said he would be willing to invoke the Insurrection Act, which allows a president to dispatch active duty military in states that are unable to put down an insurrection or are defying federal law.
Also on Thursday, a federal appeals court heard arguments over whether Trump had the authority to take control of 200 Oregon National Guard troops.
The president had planned to deploy them in Portland, where there have been mostly small nightly protests outside an ICE building.
A judge on Sunday granted a temporary restraining order blocking the move. Trump had mobilised California troops for Portland just hours after the judge first blocked him from using Oregon's Guard.
Two dozen other states with a Democratic attorney general or governor signed a court filing in support of the legal challenge by California and Oregon. Twenty others, led by Iowa, backed the Trump administration.
Trump previously sent troops to Los Angeles and Washington. In Memphis, Tennessee, Mayor Paul Young said troops would begin patrolling on Friday. Tennessee Republican Governor Bill Lee supports the role.