DEV Community

Cover image for useState everywhere? Nope!
Sanjeev Sharma
Sanjeev Sharma Subscriber

Posted on • Edited on

8 1

useState everywhere? Nope!

Hi there! Get ready to have your mind blown!!!

I want you to take a look at this code. Not much going on here.

Bad Code

In the snippet, the user can generate a random number but cannot see it. Finally, they can send it to the server.
This code works! This is how you should do it, right? Nope.

Problem

The variable/state random is never rendered on the screen. But we're using state for it. So, every time you update it, this component and all its child components will re-render. This is unnecessary and can lead to performance issues. Okay! But then how do you stop it?

Solution

Use useRef instead of useState. useRef doesn't cause re-renders. Amazing, right? Let's optimize our code now.

Good Code

It's that simple! So, now when you don't want to render something, use this trick.
I bet you didn't know we could use useRef in situations like these. ;)

Spread the word. Share it with your friends.

Thank you.

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (1)

Collapse
 
sashankr profile image
Sashank Rampalli

That’s such a cool trick, will look through my current projects to try and do this!!

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

👋 Kindness is contagious

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

Okay