It is considered defamation to slander (or libel) someone in a court hearing or in an official proceeding. However, the reason defamatory speech is allowed in such settings is to foster free and unfettered speech without fear of being prosecuted for such speech. If someone feels intimidated by the threat of a suit over what they say, they may not tell the truth or the whole truth.
And the reason these defamatory statements made in a court hearing or in an official proceeding can be reported to the public, is that public policy demands in our society that people know what is going on in court proceedings, legislative proceedings and other public official proceedings.
People in court are sworn to tell the truth, and lies told in court are considered perjury. There can be recourse for perjury - although, quite frankly, perjury charges are rare, especially in civil actions.
In addition, if in reporting any court hearing or proceeding, the report is not accurate and fair and complete, or if the report is made with malice, or if any extraneous comment, opinion or material is added, then libel charges can, in fact, arise.