📜  React JS useRef Hook(1)

📅  最后修改于: 2023-12-03 14:46:56.474000             🧑  作者: Mango

React JS useRef Hook

The useRef hook is a built-in hook in React that allows programmers to create and access references to DOM elements or variables in functional components. It returns a mutable ref object with a .current property. The value of .current can be accessed and modified without triggering a re-render of the component.

Usage

To use the useRef hook, first, import it from the react package:

import React, { useRef } from 'react';

Then, within your functional component, initialize a reference by calling the useRef hook:

const myRef = useRef();
Creating a Ref to a DOM Element

One of the most common uses of the useRef hook is to create a reference to a DOM element. This allows you to interact with the DOM element directly, without having to use traditional DOM manipulation methods.

import React, { useRef } from 'react';

function MyComponent() {
  const inputRef = useRef();

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
}

In the above example, the useRef hook is used to create a reference to the input element. When the button is clicked, the handleClick function is called which uses the inputRef.current to access the input element and calls the focus method on it.

Keeping Values Between Renders

Another useful feature of the useRef hook is that values assigned to the .current property are retained between renders. This can be helpful when you want to store a value that persists across re-renders but doesn't trigger a re-render itself.

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

function MyComponent() {
  const intervalId = useRef();
  const count = useRef(0);

  useEffect(() => {
    intervalId.current = setInterval(() => {
      count.current += 1;
    }, 1000);

    return () => {
      clearInterval(intervalId.current);
    };
  }, []);

  return (
    <div>
      <p>Count: {count.current}</p>
      <button onClick={() => clearInterval(intervalId.current)}>
        Stop Timer
      </button>
    </div>
  );
}

In this example, the useRef hook is used to create two references. The intervalId ref is used to store the interval ID returned by setInterval so that it can be cleared later in the useEffect cleanup function. The count ref is used to store and update the count value. The count value can be modified using count.current += 1, but it won't trigger a re-render.

Conclusion

The useRef hook in React provides a way to create and access mutable references to DOM elements or variables in functional components. It is useful for interacting with the DOM directly and for preserving values between renders.