Home >Web Front-end >JS Tutorial >Callback Refs vs. useEffect: When to use which

Callback Refs vs. useEffect: When to use which

Linda Hamilton
Linda HamiltonOriginal
2025-01-29 18:34:15633browse

Callback Refs vs. useEffect: When to use which In the development of

React components, side effects management and DOM interaction are critical.

and the callback Ref is two powerful tools. useEffect It is a multi -function hook to deal with various side effects, and the recovery REF provides more direct and more efficient methods in specific scenarios. useEffect

Return Ref Detailed Explanation

Return Ref allows direct access to the actual DOM element in a functional component. Pass the callback function to the

attribute of the element. This adjustment function receives the DOM element as a parameter, allowing you to: ref

    Directly operate DOM: Set the focus, adjust the size of the element, application style, and so on.
  • Interaction with the third -party library: integrated with the library of direct operation of the DOM element (such as the gallery, the canvas library).
When to use the callback Ref

    Direct DOM operation:
    • You need to set or clean up logic related to DOM (such as focus management and adjust elements). Returning REF can directly access the DOM element to achieve precise and efficient operations.
  • Third -party library:
    • Initialize or interact with the direct operation of the DOM element (such as integrated gallery, processing canvas interaction). Returning REF allows you to pass the DOM element directly to the API of the library.
  • Avoid re -rendering dependencies:
    • Dependent items may lead to unnecessary re -rendering, which affects performance. By using the callback Ref, you can avoid containing the DOM element itself in the
    • dependent array, thereby reducing the number of rendering. useEffect useEffect
  • Example: Focus Management

Example: Roll to the bottom
<code class="language-javascript">import React, { useRef } from 'react';

function InputWithFocus() {
  const inputRef = useRef(null);

  const handleRef = (element) => {
    if (element) {
      element.focus();
    }
  };

  return <input ref={handleRef} />;
}</code>

Return REF:

:
<code class="language-javascript">import React, { useState, useRef, useCallback } from 'react';

function Chat() {
  const [messages, setMessages] = useState([]);
  const messagesEndRef = useRef(null);

  const scrollToBottom = useCallback(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  }, [messages]); 

  const handleSendMessage = () => {
    setMessages([...messages, "New Message"]); 
    scrollToBottom(); 
  };

  return (
    <div>
      {messages.map((msg, index) => (
        <div key={index}>{msg}</div>
      ))}
      <div ref={messagesEndRef} />
      <button onClick={handleSendMessage}>Send</button>
    </div>
  );
}</code>

useEffect Select the correct method

<code class="language-javascript">import React, { useState, useEffect, useRef } from 'react';

function Chat() {
  const [messages, setMessages] = useState([]);
  const messagesEndRef = useRef(null);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = () => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

  const handleSendMessage = () => {
    setMessages([...messages, "New Message"]); 
  };

  return (
    <div>
      {messages.map((msg, index) => (
        <div key={index}>{msg}</div>
      ))}
      <div ref={messagesEndRef} />
      <button onClick={handleSendMessage}>Send</button>
    </div>
  );
}</code>
For direct DOM operations and avoid unnecessary re -rendering to a vital situation, it is usually preferred to recover REF.

For simpler scenes or performance is not the main point of attention, `Useeffect` is a suitable choice.
  • By understanding the advantages of callback Ref and `Useeffect`, you can effectively make wise decisions on how to manage side effects in React components and interact with DOM.

The above is the detailed content of Callback Refs vs. useEffect: When to use which. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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