FRONT END/react

7. useRef

자코린이 2023. 5. 25. 22:32

react 공식홈페이지에도 나와있지만 더 좋은 예시와 함께 정리한 블로그가 있어 추천드립니다.

https://dmitripavlutin.com/react-useref/

 

React useRef() Hook Explained in 3 Steps

React.useRef() hook creates persisted mutable values (aka references or refs). refs are used to access DOM elements.

dmitripavlutin.com

핵심 내용은 

Calling const reference = useRef(initialValue) with the initial value returns a special object named reference. The reference object has a property current: you can use this property to read the reference value reference.current, or update reference.current = newValue.

Between the component re-renderings, the value of the reference is persisted.

Updating a reference, contrary to updating state, doesn't trigger component re-rendering.

References can also access DOM elements. Assign the reference to ref attribute of the element you'd like to access: <div ref={reference}>Element</div> — and the element is available at reference.current after the component mounting.

import { useRef, useEffect } from "react";

export default function InputFocus() {
  //선언
  const inputRef = useRef();
  
  useEffect(() => {
    // Logs `HTMLInputElement` 
    console.log(inputRef.current);
    
    //update ref
	//const divElement = inputRef.current;
    //console.log(divElement);
    
    inputRef.current.focus();
  }, []);

  // Logs `undefined` during initial rendering
  console.log(inputRef.current);

  return <input ref={inputRef} type="text" />;
}

1. ref가 바뀌어도 re-rendering이 안된다.

2. re-rendering이 돼도 값이 안 바뀐다.

3. html태그안에 ref 값을 넣어 html태그에 접근할 수 있다.

'FRONT END > react' 카테고리의 다른 글

6. useEffect  (0) 2023.05.01
5. state 관리  (0) 2023.04.20
4. components  (0) 2023.04.20
3. jsx 문법 살펴보기  (0) 2023.04.20
2. react.js 설치  (0) 2023.04.19