DEV Community

Sudhanshu Shekhar
Sudhanshu Shekhar

Posted on

How to enable two way binding in react

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.

Image description

Neon image

Serverless Postgres in 300ms (!)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay