React의 useRef 후크 이해

Linda Hamilton
풀어 주다: 2024-10-11 10:45:02
원래의
198명이 탐색했습니다.

useRefHook는 렌더링 간에 값을 저장하고 DOM 요소에 직접 액세스하며 불필요한 재렌더링을 방지할 수 있게 해주는 React의 필수 도구입니다. useStateHook과 비교되는 경우가 많지만 용도가 다릅니다.

Ref Hook의 용도는 무엇인가요?

useRef 후크는 구성 요소 렌더링 간에 유지되는 값 또는 DOM 요소에 대한 참조를 생성합니다. useRefand useState의 주요 차이점은 useRefvalue를 업데이트해도 재렌더링이 트리거되지 않는다는 점이며, 이는 특정 시나리오에서 특히 유용할 수 있습니다.

  1. 값이 변경되어도 다시 렌더링되지 않습니다.
  2. 변경 가능한 값을 저장하는 데 사용할 수 있습니다.
  3. DOM 요소에 직접 액세스하는 데 사용할 수 있습니다.

기본 구문

const refContainer = useRef(initialValue);

로그인 후 복사

예 1: 렌더링 간 값 유지

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

function RenderCount() {
  const renderCount = useRef(1);

  useEffect(() => {
    renderCount.current = renderCount.current + 1;
  });

  // Inline styles
  const containerStyle = {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    height: "100vh",
    backgroundColor: "#f4f4f4",
  };

  const headingStyle = {
    fontSize: "2rem",
    color: "#333",
    fontFamily: "Arial, sans-serif",
    backgroundColor: "#fff",
    padding: "20px",
    borderRadius: "8px",
    boxShadow: "0 4px 8px rgba(0, 0, 0, 0.1)",
  };

  return (
    <div style={containerStyle}>
      <h1 style={headingStyle}>
        This component has rendered {renderCount.current} times.
      </h1>
    </div>
  );
}

export default RenderCount;

로그인 후 복사

출력

Understanding the useRef Hook in React

예 2: DOM 요소 액세스

import React, { useState, useRef } from "react";

function Timer() {
  const [seconds, setSeconds] = useState(0);
  const intervalRef = useRef(null);

  // Start the timer
  const startTimer = () => {
    if (!intervalRef.current) {
      intervalRef.current = setInterval(() => {
        setSeconds((prevSeconds) => prevSeconds + 1);
      }, 1000);
    }
  };

  // Stop the timer
  const stopTimer = () => {
    clearInterval(intervalRef.current);
    intervalRef.current = null;
  };

  // Reset the timer
  const resetTimer = () => {
    stopTimer();
    setSeconds(0);
  };

  // Inline styles
  const timerContainerStyle = {
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    height: "100vh",
    backgroundColor: "#f0f2f5", // Light neutral background
  };

  const timerDisplayStyle = {
    fontSize: "3rem",
    color: "#2c3e50", // Dark blue-gray for a professional look
  };

  const buttonStyle = {
    padding: "10px 20px",
    margin: "10px",
    fontSize: "1rem",
    backgroundColor: "#2980b9", // Professional blue
    color: "white",
    border: "none",
    borderRadius: "5px",
    cursor: "pointer",
    transition: "background-color 0.3s ease-in-out",
  };

  const buttonHoverStyle = {
    backgroundColor: "#1a5276", // Darker shade for hover effect
  };

  return (
    <div style={timerContainerStyle}>
      <h1 style={timerDisplayStyle}>{seconds} seconds</h1>
      <div>
        <button
          style={buttonStyle}
          onClick={startTimer}
          onMouseOver={(e) => (e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor)}
          onMouseOut={(e) => (e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor)}
        >
          Start
        </button>
        <button
          style={buttonStyle}
          onClick={stopTimer}
          onMouseOver={(e) => (e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor)}
          onMouseOut={(e) => (e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor)}
        >
          Stop
        </button>
        <button
          style={buttonStyle}
          onClick={resetTimer}
          onMouseOver={(e) => (e.currentTarget.style.backgroundColor = buttonHoverStyle.backgroundColor)}
          onMouseOut={(e) => (e.currentTarget.style.backgroundColor = buttonStyle.backgroundColor)}
        >
          Reset
        </button>
      </div>
    </div>
  );
}

export default Timer;

로그인 후 복사

출력

Understanding the useRef Hook in React

useState 대신 useRef를 사용해야 하는 경우

useRefi가 useState보다 더 적합한 몇 가지 시나리오는 다음과 같습니다.

업데이트 시 다시 렌더링을 실행할 필요가 없는 값을 저장해야 하는 경우(예: 타이머, 카운터 또는 추적 렌더링).
다시 렌더링하지 않고 DOM 요소에 직접 액세스하거나 수정해야 하는 경우

위 내용은 React의 useRef 후크 이해의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!