DEV Community

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

Posted on • Edited on

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.

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!!