The concept may seem like something people actively choose to engage in, but it has its roots in childhood, particularly the toddler years. Children in this stage are becoming more aware of what's around them and looking to make connections that answer their favorite question: Why? They are also in an egocentric stage of development, so it's easy for them to believe that something they do—say, wearing a blue shirt—can have an effect on something totally unrelated, such as having good weather.
As they age, higher-level cognition comes into play and kids begin to realize that an example such as this is not actually possible. Still, older children and even adults may continue some aspects of magical thinking for various reasons they may not even be aware of.
Magical thinking comes from the ego center. It is a disorder of thought content; it denotes the false belief that one's thoughts, actions, or words will cause or prevent a specific consequence in some way that defies commonly understood laws of causality.
Sigmund Freud believed that magical thinking was produced by cognitive developmental factors. He described practitioners of magic as projecting their mental states onto the world around them, similar to a common phase in child development. From toddlerhood to early school age, children will often link the outside world with their internal consciousness, e.g. "It is raining because I am sad."
Magical thinking is a type of cognitive distortion, or inaccurate thought pattern, in which individuals believe that their thoughts or actions will directly influence and produce a specific outcome, either positive or negative. Magical thinking can be a source of comfort. It can also provide a false sense of control when individuals feel distressed and out of control.
There are several cognitive distortions that people become trapped by that are usually used to reinforce negative thoughts and emotions. These thought patterns keep us stuck and lead us to have lower self-esteem and be overall more dissatisfied with our lives. Cognitive distortions are at the core of cognitive-behavioral therapy (CBT) and magical thinking is one of the common types of distortions.
https://www.verywellmind.com/magical-thinking-2671612
https://en.wikipedia.org/wiki/Magical_thinking
https://thepsychologygroup.com/magical-thinking/