Magnetic potential energy:
When a current carrying loop is placed in an external magnetic field the torque is acted upon the current loop which tends to rotate the current loop in a magnetic field. Therefore the work is done to change the orientation of the current loop against the torque. This work is stored in the form of magnetic potential energy in the current loop. This is known as the magnetic potential energy of the current loop.
Note: The current loop has magnetic potential energy depending upon its orientation in the magnetic field.
Derivation of Potential energy of currentloop in a magnetic field:
Let us consider, A current loop of magnetic moment $\overrightarrow{m}$ is held with its axis at an angle $\theta$ with the direction of a uniform magnetic field $\overrightarrow{B}$. The magnitude of the torque acting on the current loop or magnetic dipole is
$\tau=m \: B \: sin\theta \qquad(1)$
Now, the current loop is rotated through an infinitesimally small angle $d\theta$ against the torque. The work done to rotate the current loop
$dW=\tau \: d\theta$
$dW=m \: B \: sin\theta \: d\theta $ {from equation $(1)$}
If the current loop is rotated from an angle (or orientation) $\theta_{1}$ to $\theta_{2}$ then the work done
$W=\int_{\theta_{1}}^{\theta_{2}} m \: B \: sin\theta d\theta$
$W= m \: B \: \left[ cos\theta \right]_{\theta_{1}}^{\theta_{2}} $
$W= m \: B \: \left( cos\theta_{1}  cos\theta_{2} \right) $
This work is stored in the form of potential energy $U$ of the current loop :
$U= m \: B \: \left( cos\theta_{1}  cos\theta_{2} \right) $

If $\theta_{1}=90^{\circ}$ and $\theta_{2}= \theta$
$U= m \: B \: \left( cos90^{\circ}  cos\theta \right) $
$U=  m \: B \: cos\theta $

$U=  \overrightarrow{m} . \overrightarrow{B}$

Thus, a current loop has minimum potential energy when $\overrightarrow{m}$ and $\overrightarrow{B}$ are parallel and maximum potential energy when $\overrightarrow{m}$ and $\overrightarrow{B}$ are antiparallel.