Energy gives us the ability to perform physical activities

We lose Energy stored in our body while running and jogging

Energy is dissipated when an object moves from one place to another

To cause the object to move, a Force is applied to it

Work is done by the Force to displace the object from its position

The energy derived from the object due to its Motion is called Kinetic Energy

And the type of energy an object has because of its position is known as the Potential Energy

In other words, an object with potential energy has the potential to do work

Similarly, magnetic materials in a Magnetic field will possess Potential Energy which is related to the orientation, or alignment, of those materials within the Magnetic field

Let us calculate the Potential Energy of a bar magnet placed in a Magnetic Field

The bar magnet has a Magnetic Moment of $m→$ and it is placed in an Uniform Magnetic field of induction $B→$

We need to apply Torque to rotate the bar magnet

But to apply Torque on the bar magnet, Work needs to be done on it

We know that Work Done=Torque $×$ Angular Displacement

To rotate the bar magnet by an angle $dθ$, a Work done of $dW$ needs to be done which can be mathematically expressed as,
$dW=τ.dθ$

Where,
$τ$=Torque
$dθ$=Angular displacement

Torque is mathematically given by,
$τ=m→×B→∴τ=mBsinθ$

Where $m→$=Magnetic moment
$B→$=Magnetic induction

Replacing the value of Torque in the equation,
$dW=mBsinθdθ$

Now, let's say that originally the magnet is oriented at an angle $θ_{1}$ with the Magnetic Field

The bar magnet is rotated to a final angle of $θ_{2}$ with the Magnetic Field

To find the Work Done during this process, we need to integrate $dW$ within $θ_{1}$ and $θ_{2}$

Total Work Done $W=∫_{θ_{1}}dW$

$W=∫_{θ_{1}}mBsinθdθ⇒W=mB∫_{θ_{1}}sinθdθ$

$W=mB[−cosθ]_{θ_{1}}∴W=mB[cosθ_{1}−cosθ_{2}]$

It is important to note that the Work done on an object is stored in the form of Potential Energy.
Work done$(W)$=Potential Energy$(U)$

Initially the Potential Energy(U)=0 when the angle $θ_{1}=90_{o}$ as $cos90_{o}=0$

But for an angle $θ_{2}=θ$ the Potential Energy is given by $U=−mBcosθ∴U=−m→.B→$

Revision

Torque is mathematically given by,
$τ=m→×B→∴τ=mBsinθ$

Where $m→$=Magnetic moment
$B→$=Magnetic induction

Work Done $W=mB[cosθ_{1}−cosθ_{2}]$

Where,
$θ_{1}$=Initial angle made by bar magnet with Magnetic field
$θ_{2}$=Final angle made by bar magnet and Magnetic field after rotation

Work done $(W)$=Potential Energy $(U)$

For an angle $θ_{2}=θ$ and $θ_{1}=90_{0}$the Potential Energy is given by $U=−mBcosθ∴U=−m→.B→$