Heatsinks are used to prevent transistors from getting too hot. Air and plastic are a very bad heat conductors; the heat a transistor produces is not easily transferred to the surrounding air or plastic. Metal however is a very good heat conductor. That's why small power transistors have a small metal plate and large power transistors even have a full metal case. The larger the metal surface, the easier the produced heat is transferred to the ambient. And that is exacly what a heatsink does: enlarging the metal surface of a transistor.
This chapter describes how to calculate the size of the heatsink you need.