DEV Community

Cover image for Stop using useState for everything
Douglas Henrique
Douglas Henrique

Posted on

3

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 🙂

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
link2twenty profile image
Andrew Bone

When you have a form you can get data out of it quite easily by using the submit event.

Something like this.

It have the added benefit of being able to have lots of inputs in the form without needing lots of useRefs.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay