DEV Community

Tejaswa Hinduja
Tejaswa Hinduja

Posted on

Why even use React-Hook-Forms ?

Have you ever built forms for your app? If yes then you must be familiar with useState hooks re rendering your components again & again, React hook forms solved this problem , but before diving into rhf , lets first understand how did people build forms before rhf was a thing.
The ancient way was :-

What were the issues with this approach ? There was no way to have live UI updates and validations , since the data lived in the native dom element and react did not have the any information about the data until the submission.

React introduced states and this was the way to go about building forms that can support live ui updates and valdiations.

But this introduced new headaches, whenever a state variable changes they cause the component to re render , suppose we have 50 input fields and 50 state variables now every time a key is pressed the state changes and the components would re render.

React hook forms solved this , how? RHF places a ref onto the dom input element , Instead of syncing every keystroke with react state.
The rhf listens for the input events and runs a raw js script which runs the validations like number of characters , password strength , etc.
If there is a validation error then rhf sends a notification to react and only the error text component re renders , rest of the inputs remain completely untouched.
Heres a simple flow chart.

By doing this rhf avoided re rendering whole components because of change in one input state.

I hope you understood why react hook forms was even introduced.
Leave a like and connect with me on my socials
Linkedin:- https://www.linkedin.com/in/tejaswahinduja/
twitter/x:- https://x.com/Tej_Codes
github :- https://github.com/TejaswaHinduja

Top comments (0)