Some programs like vim/nano/nload has the ability to use the whole terminal to display its content and upon exiting, the previous terminal output is restored. How do they implement this restoring process?
How do they implement this restoring process?
They don't. It's not theirs to implement.
This is the so-called alternate screen buffer being switched in and out. It's implemented in the terminal (or terminal emulator program) itself. The terminal responds to control sequences that are emitted by such TUI programs. The TUI programs control when this happens, but the implementation of what happens is entirely within the terminal. Indeed, the TUI programs don't even have the same model of what is happening. To them, they are switching into and out of "cursor addressing mode".
Not all terminals and terminal emulator programs even have an alternate screen buffer. For example: the terminal emulator programs built into Linux and BSD kernels that provide their kernel virtual terminals usually don't have this capability.
On such terminals, there is no control sequence. The termcap/terminfo database record for the terminal type will, consequently, not have such control sequence; and switching to and from "cursor addressing mode" overwrites the current screen content without saving and restoring it.
vim, nano, and whatnot have no knowledge of this. They aren't doing anything different. They aren't what performs the function. They are simply emitting the control sequences that termcap/terminfo tell them will enter and exit "cursor addressing mode". For some terminals, that have the mechanism, "cursor addressing mode" also means use the alternate screen buffer. For some, that have not, it does not.