Question - Can you please tell me in which book and in which chapter this incident is mentioned?
Ans - This is not a canonical story from any authoritative Sanskrit-text.
This story is based on local (sthala) folklore or oral storytellers (kathāvācaka) traditions from and around the areas in the current state of Gujarat.
This story is NOT found in any of the known/popular Rāmāyaṇas (viz the Vālmīki, Adhyātma, Ānanda, Kamba, Kṛttivāsī Rāmāyaṇa, etc) or other authoritative texts.
On researching on this topic, I was able to trace the following source(s) to arrive at the above conclusion:
1. From the Anthology Series - Bhāratīya Bhāṣāoṃ meṃ Rāma-kathā
As per this anthology book series1 on Rāmāyaṇa stories, titled - 'Bhāratīya Bhāṣāoṃ meṃ Rāma-kathā:
Gujarātī Bhāṣā', this particular story is attributed to the 19th CE Advaitian, the Gujrati playwright and poet - Narhari Dave's composition titled - "Jaya Bajarang".
2. The book - 'The Chronicles of Hanuman' by Shubha Vilas
In their book2, 'The Chronicles Of Hanuman', writer Shubha Vilas, also agrees with this particular story being a folkloric account only, and hence, the author narrates this story under the sub-section of "Hanuman Folklore Tales" in their book.
3. From the book - 'Hanuman's Tale' by Philip Lutgendorf
In his extensively researched and well-cited book3 - 'Hanuman's Tale: The Messages of a Divine Monkey', author Philip Lutgendorf says -
Chapter 5. A Reader's guide to Hanumāyana
8. Playmate of Rama
This, too, in the view of some pandits, is an ‘‘imaginary’’ story,
since it lacks an epic or Puranic pedigree, but it is a wonderfully
charming one. It reflects popular fascination with the theme of
bāla-līlā — 'the play of deities in child form', as exemplified in the
cycle of tales concerning Krishna’s infancy and boyhood. The Madari
tale may be an effort to similarly flesh out Rama’s early youth, which
in many literary Ramayanas is passed over in a handful of verses.
The popular story of the god Śiva disguising as a Madārī (मदारी - monkey-trainer), accompanied by monkey-form Hanumāna to meet the boy-form of Śrī Rāma doesn't find any canonical scripture sanction.
: भारतीय भाषाओं में रामकथा: गुजराती भाषा. (2015). India: Vāṇī Prakāśana. Hardcopy can be purchased from here.
: Vilas, Shubha. The Chronicles of Hanuman. India: Om Books International, 2016. Hardcopy can be purchased from here.
: Lutgendorf, Philip. Hanuman's Tale: The Messages of a Divine Monkey. United Kingdom: Oxford University Press, 2006. Hardocy can be purchased from here
Search keywords: शिव कब बनें मदारी?