The spines of the cactus have several functions, which are the following:
To defend them from possible predators: inside the body of the plants there is a great deal of water; if herbivores could access it, these plants would not survive.
To provide them with shade: it is true that not much, but it is enough so that the loss of water by evaporation is minimal.
Reflect sunlight: many species have white spines.