assisrafael / react-bootstrap-utils

React bootstrap library
MIT License
6 stars 6 forks source link

Why does the Form use useState? #39

Closed CaiqueR closed 2 months ago

CaiqueR commented 3 years ago

I would like to know the reason for using useState instead of using useRef to update Form values?

Wouldn't that cause a lot of side effects? For example, each time I write an input the state is changed, thus rendering the component several times.

Libraries like formik or unform use useRef to make changes to the Form and it seems to work better. I would like to know the reason for using useState instead of useRef.

Changing state

assisrafael commented 3 years ago

There are lot of approaches to build forms. You can also check Form2 which is the new approach being developed here. But basically if you are using controlled components (https://reactjs.org/docs/forms.html) on each time a keystroke happens the component will be render again. There are a lot of libraries that use uncontrolled forms, not only the ones you listed.

CaiqueR commented 3 years ago

But why is it necessary to use useState instead of useRef? Why use this approach? Doesn't it require more of the user's processing because it is updating the state every time a key is pressed? Like the GIF above

assisrafael commented 3 years ago

With useRef you don't get automatic notifications when data change and you have to do it manually. And if a child component depends on the data to render again you will need to add extra code to do that.

CaiqueR commented 3 years ago

With useRef you don't get automatic notifications when data change and you have to do it manually. And if a child component depends on the data to render again you will need to add extra code to do that.

But wouldn't it be more interesting in terms of performance to use Ref?

assisrafael commented 3 years ago

It is a compromise. For most of use cases the performance difference is irrelevant.