본문 바로가기

국비교육/React

React 예제풀이 #03 useRef

 

 

useRef는 .current 프로퍼티로 전달된 인자(initialValue)로 초기화된 변경 가능한 ref 객체를 반환합니다.

반환된 객체는 컴포넌트의 전 라이프사이클을 통해 유지될 것입니다.

 

 

 

useRef는 저장공간 또는 DOM요소에 접근하기 위해 사용되는 React Hook이다. 여기서 Ref는 reference, 즉 참조를 뜻한다.

우리가 자바스크립트를 사용 할 때에는, 우리가 특정 DOM 을 선택하기 위해서 querySelector 등의 함수를 사용한다.

React를 사용하는 프로젝트에서도 가끔씩 DOM 을 직접 선택해야 하는 상황이 필요하다. 그럴때 우리는 useRef라는 React Hook을 사용한다.

 


 

 

이제 관련된 예제를 만들어보고 실습해볼게요 ~ 

 

 

 

 

먼저 App.js를 작성해줍니다 

 

import "./App.css";
import { useState } from "react";

function App() {
  const [name, setName] = useState("Guest");
  const [inputValue, setInputValue] = useState("");
  const hinputchange = (e) => {
    console.log(e.target.value);
    setInputValue(e.target.value);
  };

  return (
    <div className="App">
      <input type="text" value={inputValue} onChange={hinputchange}></input>
      <h1>안녕하세요 . {name}님!</h1>
    </div>
  );
}

export default App;

 

 

 

위와같이 코드를 작성하고 실행해볼게요 

 

 

안뇽~

 

 

 

 

실행을 한뒤 인풋박스에 값을 입력하면 console.log에 의해 콘솔에 값이 출력됨 

 

 

 

 

 

 

 

 

 

 

이제 인풋에서 "이름전송"버튼을 누르면 값이 전달되게끔 수정해볼게요 

 

 

 

 

 

 

import "./App.css";
import { useState } from "react";

function App() {
  const [name, setName] = useState("Guest");
  const [inputValue, setInputValue] = useState("");
  const hinputchange = (e) => {
    console.log(e.target.value);
    setInputValue(e.target.value);
  };

  const hChangeName = () => {
    setName(inputValue);
  };

  return (
    <div className="App">
      <input type="text" value={inputValue} onChange={hinputchange}></input>
      <button onClick={hChangeName}>이름전송!</button>
      <h1>안녕하세요 . {name}님!</h1>
    </div>
  );
}

export default App;

 

 

버튼을 추가해주고 자바스크립트 onClick 메소드를 이용해서 setName 을 설정 

 

 

 

 

 

 

 

 

 

 

 

이름전송 버튼을 누르니까 화면의 텍스트가 변경됨 : ) 

 

 

 

 

 

 

모듈화를 하기 위해 App( ) 전체 내용을 복사하고 상단은 BadInput( )로 이름을 변경한 뒤 

  아래는 기본골격 외에 모든 내용을 삭제 후 <BadInput/>만 입력해도 동일한 결과가 출력되게끔 수정해보자 

 

 

  • 모듈화 : 소프트웨어의 성능을 향상시키거나 시스템의 디버깅, 시험, 통합 및 수정을 용이하도록 하는 소프트웨어 설계 기법

 

쉽게 설명해서 여기 적었다 저기 적었다 해서 쉽게 호출할수있게끔 하나의 큰 틀로 만들어버리자 그냥 function화 한다고 생각하면 편하려나 

 

 

 

 

 

 

 

 

 

 

import "./App.css";
import { useState } from "react";

function BadInput() {
  const [name, setName] = useState("Guest");
  const [inputValue, setInputValue] = useState("");

  const hInputChange = (event) => {
    console.log(event.target.value);
    setInputValue(event.target.value);
  };

  const hChangeName = () => {
    setName(inputValue);
  };

  return (
    <div className="BadInput">
      <input type="text" value={inputValue} onChange={hInputChange}></input>
      <button onClick={hChangeName}>이름전송</button>

      <h1>안녕하세요. {name}님!</h1>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <BadInput />
    </div>
  );
}

export default App;

 

 

 

 

 

function 안에 이름 변경하는 기능을 담아주었다

 

출력단에서 이렇게 깔끔하게 표현할수있습니다.

 

 

 

 

 

이제 useRef 를 이용해보자 useRef를 이용해 구현한 기능은 함수명 GoodInput 으로 모듈화 해보자 

 

import "./App.css";
import { useState, useRef } from "react";

function BadInput() {
  const [name, setName] = useState("Guest");
  const [inputValue, setInputValue] = useState("");

  const hInputChange = (event) => {
    console.log(event.target.value);
    setInputValue(event.target.value);
  };

  const hChangeName = () => {
    setName(inputValue);
  };

  return (
    <div className="BadInput">
      <input type="text" value={inputValue} onChange={hInputChange}></input>
      <button onClick={hChangeName}>이름전송</button>

      <h1>안녕하세요. {name}님!</h1>
    </div>
  );
}

function GoodInput() {
  const [name, setName] = useState("Guest");
  const inputRef = useRef("");

  const refChange = () => {
    setName(inputRef.current.value);
  };

  return (
    <div className="GoodInput">
      <input type="text" ref={inputRef} onChange={refChange}></input>

      <h1>안녕하세요. {name}님!</h1>
    </div>
  );
}

function App() {
  return (
    <div className="App">
      <BadInput />
      <hr></hr>
      <GoodInput />
    </div>
  );
}

export default App;

 

 

 

 

 

쨘 

 

 

 

 

 

 

 

 

위의 BadInput과 다르게  버튼을 입력하지않아도 값을 입력하면 화면 렌더링없이 해당 값이 화면에 출력됨다

 

 

 


 

 

 

 

 

이제 또 다른 예시를 보겠습니다

 

 

 useRef 사용 예시

useRef가 유용한 상황은 이런 상황이 있습니다
예를 들어 내 컴포넌트가 몇번 렌더링됐는지 알고싶은 상황이라고 해보겠습니다.

 

 

 

function App() {
  const [count, setCount] = useState(1);
  const [renderingCount, setRedneringCount] = useState(1);
 
  useEffect(() => {
    console.log("rendering Count : ", renderingCount);
    setRedneringCount(renderingCount + 1);
  });

  return (
    <div>
      <div>Count : {count}</div>
      <button onClick={() => setCount(count + 1)}> count up </button>
    </div>
  );
}

 

 

 

 

 

 

 

 

 

 

 

이렇게 로직을 짜면, useEffect 안에있는 setRenderingCount()가 계속해서 컴포넌트를 리렌더링해서 무한 루프에 빠지게 됩니다

이를 useRef를 통해 효율적으로 관리할 수 있습니다.

 

 

 

 

 

function App() {
  const [count, setCount] = useState(1);
  const renderingCount = useRef(1);

  useEffect(() => {
    console.log("renderingCount : ", renderingCount.current);
    ++renderingCount.current;
  });

  return (
    <div>
      <div>Count : {count}</div>
      <button onClick={() => setCount(count + 1)}> count up </button>
    </div>
  );
}

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

오늘은 useRef 훅과 예시들을 풀어보았습니다 

이제 props를 마지막으로 실제 프로젝트 예제를 진행해보도록 하겠습니다