React is a one-way binding library. However, if you want to send a function or data from a child component to a parent component, you can use the useImperativeHandle
hook.
To do this, you first define a ref in the parent component and pass it to the child component, which should be wrapped in forwardRef
(although in React 19, we don't need it my bundler still have 18).
You then pass that ref to the useImperativeHandle
hook, which takes three parameters: the first is the ref, the second is a callback function that returns all the values and functions you want to transfer from the child to the parent, and the third is a dependency array. If you want to send state data, include it in the dependency array so that it will return fresh values.
Below is a demo component that logs a name from the parent, which is defined in the child component.
Top comments (0)