DEV Community

Willian Novaes
Willian Novaes

Posted on

Stop Using useState for everything!

When we learn React hooks, the first one we encounter is useState, and we’re amazed by how it updates our components and reflects the values. However, we can get lazy and start using it for everything. Over time, this can lead to performance loss and make our project heavier, often without us knowing why. Let's look at an example of a simple login page.

Image description

Every time we type a value into an input, we end up re-rendering the entire component unnecessarily. Unless we actually need to validate the inputs with every user input, there’s no need to track the value at every moment. We can capture the value and even validate it only when the user presses the submit button.

Image description

So, what can we do instead of using useState? Use useRef!

Instead of using useState, which triggers re-renders, we can use useRef to tie a reference to each input. Then, when the user submits the form, we can retrieve the values at that moment.

Image description

Or we might not even need to use useRef if we don't want to. If our form is encapsulated within a

element, we can simply pass the event as a property during form submission, and from the event object, we can retrieve the values.

Image description

I hope you found this tip useful. Feel free to comment, share your experiences, or add to this discussion. I look forward to sharing more insights on how to develop more performant applications.

Top comments (0)