Backup using TWRP, then execute the following on the Android device using the terminal spawned from TWRP. Ensure that the external SD card has more than sufficient space.

tar -cvpzf /external_sd/backup.tar.gz /data/media/0

Install new firmware or restore your backup, then install TWRP, reboot to TWRP and then execute the following on the Android device using the terminal spawned from TWRP
need to:
cd /
tar -xvpzf /external_sd/backup.tar.gz --numeric-owner

the cd / is necessary. Otherwise, the files get restored to unintended directories!