Home Web Front-end JS Tutorial React Series: useState vs useRef

React Series: useState vs useRef

Aug 21, 2024 am 06:06 AM

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.

React Series: useState vs useRef


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.

React Series: useState vs useRef

The above is the detailed content of React Series: useState vs useRef. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles