0

I am new to react and I have been checking ways of triggering a child function from my parent. So far I found two ways in the following threads.

useImperativeHandle Post by rossipedia

UseEffect - Post by bennygenel

Additionally, most examples i seen aside from the post by bennygenel are using reference to handle this issue. Which comes in the form of referencing the child object and calling it's function or through the usage of useImperativeHandle to directly reference the function itself. Hence, I am curious if ref is indeed a good way of approaching this, as there might be mutations in between causing ref to be somewhat dangerous to use. On the other hand, triggering through a props sent from the parent to the child to trigger a function useEffect seems safer as there is not a need to worry for mutations inbetween.

Please do correct me if I have misunderstood anything thanks.

WhiteSolstice
  • 641
  • 2
  • 7
  • 20
  • 2
    Any context or specific examples for why you need to trigger a child's function from the parent? There's usually a better way to accomplish some things that doesn't expose you to unexpected behavior. Or are you just curious? – Khauri Oct 10 '19 at 10:14
  • @Khauri, it's mostly curiosity, but if an example is required I can imagine that there maybe cases where the parent will trigger a function from the child as the child does not have the required state to understand when to trigger it's function. But if there are any other special/corner cases that might require a certain approach of triggering the child's function for it to function properly, it would also be great to know. – WhiteSolstice Oct 10 '19 at 15:31
  • 1
    That particular example you described is the whole reason props and useEffect exist--to pass state from the parent to the child such that the child can execute its own logic, and using an imperative handle is definitely an anti-pattern for that use case. The only actual edge case I can think of would be if your react component needed to wrap a third party api and you wanted to expose the api itself to the user so that they could use it, but if you do that you run the risk of the api's state changing and your wrapper not knowing about it, and thus being unable to update itself. – Khauri Oct 11 '19 at 12:47

0 Answers0