Stop Using useState for everything!
Willian Novaes
Posted on October 21, 2024
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.
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.
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.
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.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.
Posted on October 21, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024