Defendants cannot represent themselves unless a judge determines that they are competent to do so. The community as a whole has an interest in achieving justice. A trial in which an incompetent defendant self-represents does not constitute a fair trial.
Many defendants facing criminal charges are not in custody at the time they seek to hire an attorney. Either the police issue them a citation and a court date and never take them to jail, or they bail out of jail on their own, without first hiring an attorney.
Most criminal defendants are legally indigent and can’t afford to pay for an attorney. On the other hand, the state can’t legally prosecute indigents unless it provides them with an attorney. To satisfy this requirement, many states have set up public defender offices.