I am no expert in this but I think this is right as far as it goes. Your question is about the use of a magnetometer in space with Arduino style sensors and algorithms, so I can provide some links which will be helpful.
On earth in a local area like a room up to kilometer-sized flying radius, people try to use magnetometers to help establish a baseline for their algorithm that uses gyro signals to determine direction.
A stream of signals from a gyro might tell you that you've turned about 20 degrees ccw in the last 5 seconds, but "20 degrees from what?" is the question. The answer is "From wherever you were pointing five seconds ago." As long as you are flying gyros-only you have to keep adding every change to the list of previous changes to see where you are pointing now.
Gyros always have errors and offsets, they can think they are spinning when they aren't, can be nonlinear and can mix rotations in different axes together incorrectly or misinterpret accelerations as rotations, especially the ones we use with hobby projects.
So people turn to our friend the Earth and its stable magnetic field because it tends to point in a fixed direction locally.
When the accumulated gyro errors start deviating too much from the compass direction too much, the attitude is combined with, or reset to the compass information as best as it can be guessed. Every algorithm is different.
The problem is that the compass can not tell you anything about rotation around the magnetic field direction, which at mid-latitudes points diagonally up out of the ground.
Luckily our friend the Earth gives us a second stable field as well, gravity!1 We can use the axis of the local magnetic field and the axis of the local gravitational field to build a non-rotational fixed frame.
Any ferromagnetic materials like iron in the ground or rocks or buildings (e.g. rebar in reinforced concrete) will distort the local magnetic field.
And the Earth plays games with its magnetic field as well!
as do other planets!
Low cost hobby or cellphone compass modules are suboptimal:
As are the accelerometers:
The implementation of gyros (sometimes together with accelerometers) for absolute pointing is sometimes called a gyrocompass.
Great flying often involves the incorporation of several different streams of data from very different sources. Motion detection and patter recognition from vision systems are used by insects and birds and some drone flying algorithms, radar (radio or acoustic pings) doppler (radio, audio), laser scanners for field mapping can and have all also be explored at the hobby level as well.
1note added in proof; "down" from gravity is not available to those in orbit!