How does the dedication of merit work, according to the texts?

Please explain how this dedication of merit works according to you

Merit isn’t “transferred” but shared. Essentially the devas or pretas are invited to share in the rejoicing. Suitable occasions for this would be after meditiation, after taking the precepts, listening to a sermon or after giving gifts.

And it is also foreign to Theravada and they adopted it too?

They aren’t foreign to Theravāda.