I believe that those who have used React ref will be familiar with --- 7ce6c653bb51ecf822fa0fa9d0b812b3---, which can be used to obtain component instance objects or DOM objects.

And useRef this hooks function, in addition to traditional usage, it can also save data "across render cycles" .

Let's first 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 the couterRef object and assign it to the button cdb454c9 attribute of ref . In this way, by accessing couterRef.current , you can access the button corresponding DOM object.

Then look at the usage of it to save data.

Is there anything in a component that can span render cycles, i.e. properties that persist 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 be rendered the same after multiple renders. However, the problem with state is that once it is modified it will cause the component to re-render.

Then at this time, you can use useRef to store data across the rendering cycle, and modifying it will not cause the component to render.

 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 above example, I use the ref current object to store the timer ID, so that the timer ID can be saved after multiple renderings, so that it can be cleared normally timer.

For more front-end knowledge, please pay attention to the applet, there will be surprises from time to time!
image.png


anchovy
1.9k 声望89 粉丝