[React] Ref

오리·2024년 4월 21일
post-thumbnail

1. Ref란?

  • 컴포넌트가 리렌더링 되어도 값을 유지하고 싶을때 사용한다.
  • Ref값이 변경되어도 해당 컴포넌트가 리렌더링 되지 않는다.
  • 컴포넌트 내부에서 선언과 사용된다.
  • DOM을 직접적으로 건드려야 할 때 사용한다.
    -> 특정 input에 focus 주기, 스크롤박스 조작, 비디오플레이어의 재생/정지 기능 등
  • Class형 컴포넌트에서만 기본 기능으로 제공한다.

2. useRef

  • 함수형 컴포넌트에서 ref를 사용하려고 할 때 useRef 사용한다.

1) current

  • current 속성으로 실제 요소에 접근한다.
  • ref.current.focus() 이용할 수 있다.
    -> 특정 동작(onClick)시 input창에 focus를 줄 수 있다.
  • ref.current로 접근하여 다양한 속성을 제어할 수 있다.

3. variable vs state vs ref

  • variable (변수) : 렌더링 될 때마다 초기화
  • state : state 값 변경시 리렌더링
  • ref : ref값은 변경되어도 리렌더링 되지 않는다.

1) 실습

  • 변수, state, ref를 사용하여 비교해보자!

함수형

import {useRef, useState} from "react";

export default function FunRef() {
	// react에서 dom요소 조작하기 위해 변수 선언
	const input = useRef();
    
    // 인풋창에 focus 하는 함수
    const focusInput = () => {
    // dom요소에 직접적으로 접근!
    	input.current.focus();
    }
    
    // ref를 변수로 사용(초기값 0)
    const localVar = useRef(0);
    // state
    const [state, setStateVar] = useState(0);
    // 일반 변수
    let justVar = 0;
    
    // localVar (ref사용) 증가하는 함수
    const inCreLocalVar = () => {
    	localVar.current++;
        console.log("localVar.current: " + localVar.current );
    };
    // JustVar (변수 사용) 증가하는 함수 
    const inCreJustVar = () => {
    	justVar++;
        console.log("justVar : " + justVar);
    };
    
    return (
    	<>
    		<input type="text" ref={input} />
            <button onClick={focusInput}>버튼</button>
            
            <h2>localVar.current : {localVar.current}</h2>
            <h2>state: {state}</h2>
            <h2>justVar : {justVar}</h2>
            <button onClick={inCreLocalVar}>local+1</button>
            <button onClick={()=>setStateVar(state+1)}>state+1</button>
            <button onClick={inCreJustVar}>justVar+1</button>
    	</>
    );
}

클래스형

import {Component, createRef} from "react";

export defualt class ClassRef extends Component {
	input = createRef();
    localVar = createRef();
    state = {
    	state : 0,
    };
    
    render() {
    	return (
        <>
          <h2>클래스형 컴포넌트에서 ref 사용</h2>
          <input type="text" ref={this.input} />
          <button onClick={()=> this.input.current.focus()}>버튼</button>
          <br />
          <div>this.localVar.current : {this.localVar.current}</div>
          <div>this.state.state: {this.state.state}</div>
          <button onClick=this.localVar.current++>localVar + 1</button>
          <button onClick={()=>this.setState({state:this.state.state+1})}>state + 1</button>
        </>
    );
  }
}

-> 결론적으로, ref사용한 경우에는 리렌더링 되는 방식이 아니다보니, state눌렀을때 리렌더링되어 업데이트 되고 화면에 표시되는 형태가 된다!

profile
암튼 해보는 개발자호소인

0개의 댓글