DEV Community

Cover image for A Quick Guide to React's useState and useRef
Bibi
Bibi

Posted on • Updated on

A Quick Guide to React's useState and useRef

When you're starting out, useState and all of its quirks can be overwhelming enough. Now throw useRef into the mix and you get a loud brain explosion.


I thought it would be helpful to dive a bit deeper into the technicalities of useRef vs useState, as engineers usually have a hard time understanding the differences between them and when to choose one over the other.

Here are my definitions for each, in broad strokes and obviously oversimplified:

useState is a hook that lets you access and update a value, triggering a re-render.

useRef is a hook that lets you reference a value that’s not needed for rendering.


You might be asking yourself, why is it important to understand what each of these bring to the table? Well, you might be tempted to slap useState into everything, simply because it does work.

Yes, HOWEVER, the more complex your app becomes with components passing state props 5 levels down, triggering a bunch of unnecessary updates along the way, you're probably going to start running into performance issues sooner than you imagine.

Another misconception a lot of devs have is thinking that useRef can only manipulate and access DOM elements, which is sad because y'all are missing out on the other 99 things¹ useRef can do.

Let's start with useState! Keep your ears open now, my dear dev ʕ◉ᴥ◉ʔ


useState

useState is a powerful but easy way to update the view once a variable's value changes, it keeps the latest value synchronized with the screen without manually performing any operations ourselves. The declaration syntax goes like this const [memesILiked, setMemesILiked] = useState(9000).

Now, let's talk about what happens under the hood when you perform an operation with useState.

Updating a state value triggers a re-render, and as you might imagine, re-rendering the view is a VERY expensive operation for the browser to handle. Here's how React and the browser operate in conjunction to make sure your app is updated:

  1. Event Trigger: An event triggers a state update. A click, timer or anything really.
  2. State Update: setState is called and schedules an update for the component, the component is marked as "dirty" (needing re-render).
  3. Reconciliation Phase: React starts the reconciliation between the new virtual DOM and the old virtual DOM. It recursively re-renders the component and all of its children.
  4. Checking the differences: React compares the new virtual DOM tree with the previous one. The changes are stored in a list of updates to be applied to the real DOM.
  5. Render Phase: The render method or function component is called with the new state.
  6. Commit Phase: React applies the changes from the diffing process to the real DOM.
  7. Update the DOM: The real DOM is updated to reflect the new state. The browser re-paints the DOM, visually updating the UI.
  8. Post-render Effects: Any effects that were scheduled to run after the component was re-rendered are called. This includes useEffect hooks that were registered with dependencies that changed during the render.

Phew, that's a lot of stuff... While the above process ensures that your UI stays in sync with your application state, it also highlights why excessive or unnecessary re-renders can lead to performance issues. Luckily, React provides several strategies and tools to help optimize this process, like useMemo and useCallback, but that's beyond the scope of this article!

In summary, useState is a pretty handy hook, and when used right, it can provide the user a great experience. Take theme toggling, for example. With useState, you can easily switch between light and dark modes, giving your users that instant gratification of seeing the app transform based on their preferences.


useRef

Now, let’s talk useRef. While useState is all about triggering re-renders when state changes, useRef is like the quiet observer that never wants to draw attention to itself. It's perfect for storing mutable values that don't require a re-render when they change. The syntax looks like const memeRef = useRef(null).

useRef is most often used for accessing DOM elements directly. For instance, if you need to focus an input field programmatically, useRef can hold a reference to that element. But useRef's capabilities go beyond just DOM access. It can also store any mutable value! And this, my friends, is where the magic happens 🪄🪄🪄 (in my opinion anyway).

Think of it like this: useRef is a way to persist values across renders without triggering a re-render. This makes it perfect for storing data like timers, counters, or even the previous state of a component. Unlike useState, updating a ref doesn't notify React to re-render your component. It just quietly updates the value and carries on with its business.

Here's a practical example: let's say you want to implement a simple counter, but you don’t want the UI to update every time you increment the counter. You could use useRef to store the counter value. The counter would increment as expected, but because the component doesn’t care about this ref value for rendering purposes, no re-rendering would happen.

useRef is also great in preserving the latest value of a state without causing additional renders. For example, if you're using an interval to update a value, but you don't want that value to trigger a re-render every millisecond, useRef is your go-to tool. It allows the value to change in the background, keeping your UI responsive and avoiding unnecessary re-renders.

In summary, useRef is best used for:

  • Accessing DOM elements: Classic use case, like focusing an input field.
  • Storing mutable values: That don't require re-rendering, such as timers or previous values.
  • Maintaining values across renders: Without causing a re-render, keeping your UI smooth and efficient.

Now that you HOPEFULLY understand the difference (if I've done my duty correctly²), let's dive into a few not-so-common use cases. I will focus on useRef a bit more as I feel like it's the unsung hero here.

  1. Tracking Component Mounting Status: useRef can be used to track whether a component is mounted or unmounted, this can be useful for avoiding state updates after unmounting.

  2. Holding Static Values: For storing static values that don't change between renders, like a constant or a cached value, useRef is more efficient than useState.

  3. Preventing Re-Initialization: If you want to prevent a piece of code from re-running every render (for example, initializing a WebSocket connection).

  4. Storing Previous Callbacks: If you need to keep a reference to a previous callback function, useRef can store the previous function reference without affecting the component's rendering cycle.

  5. Referencing Timer IDs: When working with timers (like setTimeout or setInterval), store the timer ID in a useRef to avoid triggering a re-render every time the timer is set or cleared.

  6. Triggering Animations: For triggering animations imperatively (like a CSS transition or scroll animation), useRef can be used to directly interact with DOM elements without causing re-renders.


Conclusion

While useState is crucial for managing and reacting to state changes that should trigger re-renders, useRef is the silent partner that helps you manage state without disrupting the UI.

Knowing when to use each can save you from potential performance issues and make your React applications more efficient and maintainable!


Thanks for reading, if you made it here, PAWS UP AND HIGH FIVE! ⊹⋛⋋( ՞ਊ ՞)⋌⋚⊹


Footnotes:
¹ Obviously an exaggeration.
² I'm a bit dramatic, in case you couldn't tell.

cat paw waving goodbye

Top comments (1)

Collapse
 
yourtechbud profile image
Noorain Panjwani

Mahn! I didn’t know that we could use useRef beyond accessing DOM elements. That’s crazy!

Nicely done, Bi! Love it!