Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on

     

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.

TheonChange function will set a state every time the user presses a key on keyboard. It means the app will re-renderevery 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 🙂

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
link2twenty profile image
Andrew Bone
A British web developer, that is passionate about web accessibility.
  • Location
    Britain, Europe
  • Pronouns
    He/Him
  • Work
    Senior Web Developer at bloc-digital
  • Joined

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 ofuseRefs.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

JS full stack developer | React, Node JS and React native 🇧🇷
  • Location
    São José dos Campos, São Paulo, Brazil
  • Work
    Frontend specialist at Árvore
  • Joined

More fromDouglas Henrique

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp