Sum of residuals and Matrix calculus (step by step)
Let $\mathbf A,\mathbf B$ be $m\times n$ matrices (or vectors is either $m$ or $n$ is $1$), 
\begin{align}
(\mathbf A+\mathbf B)^T&amp;=\mathbf A^T+\mathbf B^T \tag{1}\\
(\mathbf A\mathbf B)^T&amp;=\mathbf B^T\mathbf A^T \tag{2}
\end{align}

Thus, 
\begin{align}
(\mathbf y-\mathbf X\beta)^T(\mathbf y-\mathbf X\beta)&amp;=(\mathbf y^T-(\mathbf X\beta)^T)(\mathbf y-\mathbf X\beta)\\
&amp;=(\mathbf y^T-\beta^T\mathbf X^T)(\mathbf y-\mathbf X\beta)\\
&amp;=\mathbf y^T(\mathbf y-\mathbf X\beta)-\beta^T\mathbf X^T(\mathbf y-\mathbf X\beta)\\
&amp;=\mathbf y^T\mathbf y-\mathbf y^T\mathbf X\beta-\beta^T\mathbf X^T\mathbf y+\beta^T\mathbf X^T\mathbf X\beta \\
&amp;=\mathbf y^T\mathbf y-2\mathbf y^T\mathbf X\beta+\beta^T\mathbf X^T\mathbf X\beta \tag{3}
\end{align}
where line 1 uses $(1)$, line 2 uses $(2)$, and the last line follows from the fact that $\mathbf y^T\mathbf X\beta$ and $\beta^T\mathbf X^T\mathbf y$ are both $1\times1$ scalars. 



Let $\mathbf a,\mathbf x$ be $n\times 1$ vectors and $\mathbf A$ a symmetric $n\times n$ matrix. Matrix calculus has the following rules: 
\begin{align}
\frac{\mathrm d\ \mathbf a^T\mathbf z}{\mathrm d\ \mathbf z}&amp;=\mathbf a \tag{4} \\
\frac{\mathrm d\ \mathbf z^T\mathbf A\mathbf z}{\mathrm d\ \mathbf z}&amp;=2\mathbf A\mathbf z \tag{5}
\end{align}

Applying these to differentiating $(3)$ with respect to $\mathbf\beta$, we get the first order condition:
\begin{equation}
-2\mathbf X^T\mathbf y+2\mathbf X^T\mathbf X\beta=0
\end{equation}
Solving for $\beta$, we get the usual OLS formula.