I think we have a strong subconscious desire to belong in groups, and one of our instinctive behaviors is to protect the group from outsiders. Many animal species display this same behavior, and some ape species will even form groups that will physically attack (and even kill) outsiders from the same species.
You can see how strong this impulse is, in the way we easily form groups to support almost any person or cause. Around the world, people will belittle and insult one another because they support a different sports team, to the extent that some people have been physically assaulted and even killed over something that should be utterly trivial. Religion is perhaps our most extreme example of this form of tribalism, in that we deliberately coded in the life and death consequences of our choices. It's what makes it a particularly dangerous form of that behavior.
But I feel that it is inevitable that we would have invented religion. In some ways, we are programmed to act religiously.