Stop using useState for everything

The useState hook was created to help us to store data and update the UI all the times that the data changes. But, every time the state changes, it causes a re-render on your app and this could be a problem.

Let's take a look on the code below

Image showing a react code with useState

You might be thinking: β€œIt works, there's nothing wrong, right?” - The answer is: no.

The onChange function will set a state every time the user presses a key on keyboard. It means the app will re-render every time the user types a letter.

And as we can see, our app is re-rendering unnecessary. πŸ‘‡πŸ½

Image showing an app re-rendering many times

*So, we gonna fix that using the useRef hook.

Why?

First: the useRef allow us to get the input value without setting a state every time the user types a letter.

Second: We gonna use the useRef because we don't need to update the UI. If wee need to update UI, we must be using useState.

Image showing how to use useRef

As you can see, we don't need to set a new state on the onChange event and our application just render one time, like the picture below:

Image showing the result of using useRef

β€œBut Douglas, the app is rendering twice πŸ˜­β€** - Yes, the React Strict mode is enabled and it renders twice just to detect any problem in the app. It only runs on debug mode, so in production will gonna be safety πŸ™‚

So, it works! Your app is happy. Now we have the entire input value without rendering so many times.

Bye πŸ™‚