At first glance this story seems out of place in a holy book, but stories like this give sinners like us hope.
Judah has turned his back on his family, God, and culture. This could be because of the guilt of selling Joseph into slavery and the suffering he has caused his father. He fulfills his desires and starts a family.
His family starts to disintegrate. His firstborn was wicked in the Lord's sight and died (however, Judah has no spiritual discernment in the matter). As was common in those days, they followed levirate marriage to allow the deceased son to have an heir and take care of his widow. His second son made it seem that he was fulfilling his duty but secretly was actively trying to do the opposite. God saw this and killed him for his wickedness.
Trials can make you bitter or better. Judah (due to being spiritual dead) believes Tamar is the cause of his first two sons' deaths and doesn't want to allow his last son to be with her. Then his wife dies.
Tamar is actually a tragic figure in this story, suffering much from the men in her life. She sees what is going on and plays deception with deception; she doesn't do this out of lust or money: she wanted to have a son from the line of Judah. She convinces him to hand over items which prove his identity, their importance ensures he will pay her. Judah is unable to find her to pay her and get back his items; he has lived a life of doing bad things and then carrying on. Hearing of her pregnancy, Judah is quick to pass judgment on her and forget his own sin. Learning the truth of the matter causes him to acknowledge his guilt and take responsibility.
Out of Judah's line the Messiah would come. God did not choose Judah because of his good character, He would redeem His people. None of us are without sin and none of us are beyond His grace.