Member-only story

Call child component method from parent — React

--

Photo by Mohamed Awwam on Unsplash

There will instances that we need to directly call the child method from the parent,

Need to call child handleSubmit on click of parent button

There are couple of ways to do it

useImperativeHandle

useEffect

useImperativeHandle

Parent ref current will now have the object which returned from child

Steps

  • useRef in parent component
  • pass the ref to child
  • wrap child component with forwardRef so that parent can access child component
  • useImperativeHandler
  • — first argument should be parent ref
  • — second argument should handler function
  • handler function should return an object which is merged to the ref.current of parent
  • Now parent have access to child methods which are exposed with handler function of useImperativeHandler

useEffect

Incrementing the parent state which causing re-render in parent and child, so useEffect of the child is called which in turn calls parent function

When to use what?

It is a personal choice, but I prefer useImperativeHandle because

  • We can scale easily to multiple functions call
  • No extra state is required in parent

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet