The question has been asked by critical scholars, "Why insert the story of Genesis 38 in between the story of 37 and 39, which it interrupts?" Indeed, the Joseph novella appears to flow well beside the insertion of the Judah and Tamar narrative. Note that although I hold the Bible to be God's Word, I will be examining the question from a literary angle. Besides Judah, the cast and setting is different than what we find in the Joseph novella. It is important to note that simply because a text appears out of place does not necessitate that it is. Consider the example of King David and the prophet Nathan. Nathan recounts an anecdote to King David in 2nd Samuel 12, but until Nathan makes clear the point of relaying the anecdote, David does not truly understand. Rabbinic literature (such as Genesis Rabbah 85:2) also recognizes the issue yet is dismissive of the included text and determines that it is not a crucial part of the Joseph novella.
However, I would contend that Genesis 38 is an essential part of the Joseph novella, and that it is itself a sort of type-scene. One of the ancient literary devices utilized in the text is called anagnorsis, which refers to the moment when a character's identity becomes aware of the identity of another character. One example of anagnorisis is in the Greek tale of Oedipus, when he finally realizes the identity of his mother and father. Now, the Joseph novella itself contains several type-scenes that would have been familiar to the audience of the time, such as a scene at the well, trouble amongst brothers, preservation of family, and so forth. A type scene (or literary motif) is essentially a scene that is repeated in different forms - Isaac's wife is found by a well, Moses saves the women by the well, Saul is searching by the well, and Jesus talks with the Samaritan woman by the well. In this case, Judah sends Tamar home as a widow and does not intend on ever giving her his third son. Likewise, Joseph's brothers sell him into slavery and never expect to see him again.
Subsequently, Tamar's deception results in the reconciling of family members just as Joseph's deception of his brothers ultimately results in the reconciling of the family. Both the Joseph novella and the Judah/Tamar narrative have scenes of anagnorisis which remind the other character(s) of past mistakes - Judah is reminded of his wrongdoing just as his brothers are later reminded of what they did to Joseph. In fact, we could say that Genesis 38 is a sort of type-scene setting up the Joseph novella. It can be used as a sort of lens that will better enable us to view the much larger story. It can also be seen as a sort of payback for what Judah did to his brother Joseph in the prior chapter, as well as a sort of "meanwhile, back at the Batcave" inclusion before returning to Joseph's predicament.