Putting aside any theories around the "Cult of Silicon Valley", the typical answer I get when I ask others that same question is that "tech" companies group in these areas, especially SF, because it makes it easier to get the best talent; since everyone already lives in the same area, there's hypothetically no moving expenses that would stop candidates from accepting a job, especially when it comes to candidates with families.
Personally, I don't completely buy that explanation, and think there's an unspoken cult-like quality to the tech scene of SF/SV that confines it to a few cramped spaces in the country. Big "tech" still represents the modern form of the American Dream and the Gold Rush to countless people, and San Francisco is symbolic of that idealism in and of itself. Making six figures and living in the outskirts working for a company nobody's heard of isn't as cool as working for Unicorn X in Mountain View, CA.