In the theory section, you present the ideas that you want to test in the empirical part of your research. The best way to develop your theory section depends on the availability of data. If you must work with a given dataset, the best way to go forward is to look at the variables in your data, and draw a causal model including the variables that are at the heart of your research. You can read more about causal models here and here.

If you can collect your data yourself, e.g. by conducting an experiment, a survey, or interviews, the best way to go forward is to
read a recent literature review on your research problem and work from there. If there is no literature review available on your research problem, you will need to write that review yourself. Read more about literature reviews here.

When to write it
Remember to work in the right order (more about that here). So the first advice I would like to give you is: write the theory section first, before you have collected or analyzed your data. Identify the theories that are most relevant for your research, and narrow down broad concepts to variables that you can measure. Write down the hypotheses that you will test before you have seen the data, for instance as part of a preregistration (see here).

Writing your theory section before you have analyzed, seen or even collected the data avoids HARKING: Hypothesizing After Results are Known (Kerr, 1989). It is all too easy to paint a target after you have fired your guns and then claim you were 100% accurate.

Source: https://www.bayesianspectacles.org/origin-of-the-texas-sharpshooter/

Your hypotheses are ex ante predictions based on theories, not post hoc interpretations of your data. Preregistration of your research questions and hypotheses proves that you have not been harking. Preregistration forces you to think hard about your predictions. About which ones are you really confident? These are the predictions that belong in your theory section as hypotheses. You will probably be interested in many more relations in the data, without having a clear idea about their sign or strength. These are analyses that you can plan as exploratory analyses, without specifying a hypothesis about them.

The goal of formulating a hypothesis is not to maximize the chance that the analysis will confirm it, but to maximize the implications of testing it. By only formulating a hypothesis when there is a strong theoretical foundation for it, a rejection of the hypothesis by an empirical test is more informative. When the foundation for a hypothesis is shaky to begin with, we do not learn much from a rejection.

Reference

Kerr, N.L. (1989). HARKing: Hypothesizing After Results are Known. Personality and Social Psychology Review, 2: 196-217. https://doi.org/10.1207%2Fs15327957pspr0203_4