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

Vue3+TypeScript encapsulates axios and implements request calls

No way, no way, it turns out that there are peopl...

Detailed process of deploying Docker to WSL2 in IDEA

The local environment is Windows 10 + WSL2 (Ubunt...

Use Angular CDK to implement a Service pop-up Toast component function

Table of contents 1. Environmental Installation 2...

How to deploy hbase using docker

Standalone hbase, let’s talk about it first. Inst...

Linux nohup to run programs in the background and view them (nohup and &)

1. Background execution Generally, programs on Li...

React Hooks Detailed Explanation

Table of contents What are hooks? Class Component...

Detailed introduction of Chrome developer tools-timeline

1. Overview Users expect the web applications the...

Install mysql5.7 on Ubuntu 18.04

Ubuntu 18.04 installs mysql 5.7 for your referenc...

Tips for creating two-dimensional arrays in JavaScript

Creation of a two-dimensional array in Js: First ...

Syntax alias problem based on delete in mysql

Table of contents MySQL delete syntax alias probl...

Implementation script for scheduled database backup in Linux

Table of contents Scenario: The server database n...