To understand when to use that vs. which, it’s important to keep in mind the difference between and restrictive and nonrestrictive clauses. In formal American English, that is used in restrictive clauses, and which in used in nonrestrictive clauses.
A restrictive clause contains information that limits the meaning of the thing being talked about. For example, in the sentence “Any book that you like must be good,” the relative clause “that you like” is restrictive because it identifies specifically a book that you like. Note that in restrictive clauses, sometimes that can be omitted. “Any book you like must be good” is also often used, especially in informal settings.
A nonrestrictive clause, on the other hand, is used to supply additional information that is not essential to understanding the main point of the sentence. Consider the example “The book, which I found at a dusty used bookstore, was a real page-turner.” The relative clause “which I found at a dusty used bookstore” is nonrestrictive because it adds extra information, almost like an aside. You could delete the details about the bookstore, and the sentence would still make sense. In this example, which is preceded by a comma; nonrestrictive clauses tend to follow punctuation like a comma, a dash, or parenthesis. Which is only used in restrictive clauses if it’s preceded by a preposition.
Luckily there’s an easy way to remember whether to use that or which. If the relative clause contains information that is not essential to the meaning of the sentence, and is also preceded by a comma, a dash, or parenthesis, it’s probably nonrestrictive, so use which. If not, odds are it’s restrictive, so use that.
However, the above distinction is a rule of formal American English, and is not as strictly observed in British English or in informal English of any type.