Sometimes, though the evidence is mixed and cramp has several possible causes. If your intake is low, correcting that is reasonable and worth trying. If your diet already supplies plenty, magnesium is less likely to be the answer, and hydration, sodium and training load are worth looking at instead.