Specific use of useRef in React

Specific use of useRef in React

I believe that people who have experience with React will be familiar with ref, which can be used to obtain component instance objects or DOM objects.

In addition to the traditional usage, the useRef hook function can also save data "across rendering cycles".

First, let's look at its traditional usage:

import React, { useState, useEffect, useMemo, useRef } from 'react';

export default function App(props){
  const [count, setCount] = useState(0);

  const doubleCount = useMemo(() => {
    return 2 * count;
  }, [count]);

  const couterRef = useRef();

  useEffect(() => {
    document.title = `The value is ${count}`;
    console.log(couterRef.current);
  }, [count]);
  
  return (
    <>
      <button ref={couterRef} onClick={() => {setCount(count + 1)}}>Count: {count}, double: {doubleCount}</button>
    </>
  );
}

The code uses useRef to create a counterRef object and assigns it to the ref attribute of the button. In this way, by accessing couterRef.current, you can access the DOM object corresponding to the button.

Then let's take a look at how to save data.

Is there anything in a component that can survive across render cycles, i.e. properties that remain constant after the component is rendered multiple times? The first thing that comes to mind should be state. That's right, a component's state can remain unchanged after multiple renderings. However, the problem with state is that once it is modified, it will cause the component to re-render.

At this time, useRef can be used to store data across rendering cycles, and modifying it will not cause component rendering.

import React, { useState, useEffect, useMemo, useRef } from 'react';

export default function App(props){
  const [count, setCount] = useState(0);

  const doubleCount = useMemo(() => {
    return 2 * count;
  }, [count]);

  const timerID = useRef();
  
  useEffect(() => {
    timerID.current = setInterval(()=>{
        setCount(count => count + 1);
    }, 1000); 
  }, []);
  
  useEffect(()=>{
      if(count > 10){
          clearInterval(timerID.current);
      }
  });
  
  return (
    <>
      <button ref={couterRef} onClick={() => {setCount(count + 1)}}>Count: {count}, double: {doubleCount}</button>
    </>
  );
}

In the example above, I use the current property of the ref object to store the timer ID, so that the timer ID can be saved after multiple renderings, so that the timer can be cleared normally.

This is the end of this article about the specific use of useRef in React. For more relevant React useRef content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed example of using useState in react
  • Introduction to useRef and useState in JavaScript

<<:  Detailed explanation of Nginx installation, SSL configuration and common commands under Centos7.x

>>:  Detailed explanation of Mysql transaction processing

Recommend

MySQL joint table query basic operation left-join common pitfalls

Overview For small and medium-sized projects, joi...

How to quickly build a LAMP environment on CentOS platform

This article uses an example to describe how to q...

Full HTML of the upload form with image preview

The upload form with image preview function, the ...

Two ways to visualize ClickHouse data using Apache Superset

Apache Superset is a powerful BI tool that provid...

Detailed tutorial on replacing mysql8.0.17 in windows10

This article shares the specific steps of replaci...

Summary of vue's webpack -v error solution

Xiaobai learned about Vue, then learned about web...

IDEA configuration process of Docker

IDEA is the most commonly used development tool f...

JavaScript to achieve Taobao product image switching effect

JavaScript clothing album switching effect (simil...

MySQL Constraints Super Detailed Explanation

Table of contents MySQL Constraint Operations 1. ...

Linux tutorial on replacing strings using sed command

To replace a string, we need to use the following...

Detailed explanation of mandatory and implicit conversion of types in JavaScript

Table of contents 1. Implicit conversion Conversi...

Detailed tutorial on deploying Django project under CentOS

Basic Environment Pagoda installation service [Py...

Problems with using wangeditor rich text editing in Vue

wangEditor is a web rich text editor developed ba...

How to insert a link in html

Each web page has an address, identified by a URL...

How to use CSS to display multiple images horizontally in the center

Let me first talk about the implementation steps:...