It's fairly simple. That introduces essential clauses while which introduces nonessential clauses. And, as you know, essential clauses do not have commas surrounding them while nonessential clauses are surrounded by commas.
However, if this, that, these, or those has already introduced an essential clause, you may use which to introduce the next clause, whether it is essential or nonessential.