Member-only story
Call child component method from parent — React
Jun 23, 2023
There will instances that we need to directly call the child method from the parent,
There are couple of ways to do it
useImperativeHandle
useEffect
useImperativeHandle
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
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