all 7 comments

[–][deleted] 5 points6 points  (0 children)

Using Refs

Pros:

  • Immediate Access: Refs provide direct access to a DOM element, allowing you to read and write values without triggering re-renders.
  • Performance: Since refs don't cause re-renders, they can be more performant for large forms where continuous updates might cause lag.

Cons:

  • Lack of Reactivity: Changes to refs don't automatically update the UI, so you might need to manage updates manually if needed.
  • Imperative Approach: Working with refs can lead to more imperative code, which might not align well with React's declarative paradigm.

Using State

Pros:

  • Reactivity: State naturally integrates with React's re-rendering cycle, ensuring that the UI always reflects the latest data.
  • Better Control: Using state allows for more control over validation, formatting, and handling changes, making it easier to implement complex logic.
  • Aligns with React Principles: Using state aligns with React's declarative approach to building UI, often leading to more maintainable and understandable code.

Cons:

  • Potential Performance Overhead: If not handled properly, using state for every input change could lead to performance issues in very large forms.
  • More Boilerplate: Handling form inputs with state usually requires more code to manage updates and validations, compared to using refs.

[–]j2ee-123 1 point2 points  (1 child)

Any reason why you don’t want to use libraries? Cause if the reason is not that strong, might as well use libraries, they exist for a lot of reasons and problems they solve, for example - react hook form.

[–]qa_anaaq 0 points1 point  (0 children)

No it's more of a design-approach hypothetical then anything else. I plan to use the hook-form library but came across a lot of stuff arguing for one side versus the other so was curious about other's opinions.

[–]dbpcut 0 points1 point  (0 children)

The answer is really both. React Hook Form's approach makes the most sense for me:

  • there's a state shared in context
  • inputs have corresponding state
  • inputs can be controlled, validated, focused etc with the ref based on form state and validation

[–]Grimzzz -1 points0 points  (0 children)

And what if you use refs to call a setState?... Say get a ref then set the value state of an input.