[리액트] useRef, useEffect

돗개·2020년 11월 23일
2

React

목록 보기
2/2
post-thumbnail

리액트에 내장된 Hook에 대해 더 알아보자.

useRef 란?

특정 DOM을 가리킬 때 사용하는 Hook 함수.
Ex. 포커스 설정, 특정 엘리먼트의 크기/색상 변경 등..


ref

: ref는 JS의 getElementById()처럼, component의 어떤 부분을 선택할 수 있게 해주는 방법이다.
리액트에 있는 모든 component는 reference element를 가지고 있어서,
어떤 component에 ref={변수명} 을 넣어주면, 해당 component를 참조하게 된다.


useRef 사용하기

3초 뒤에 input창에 포커싱이 되도록 설정해보자.

import React, { useRef } from "react";

const App = () => {
  // 1. Ref객체 만들기
  const here = useRef();
  2. focus( ) DOM API 호출
  setTimeout(() => here.current.focus(), 3000);
  return (
    <div>
      <h1>Hello</h1>
      // 2. 원하는 곳에 ref 값으로 설정하기
      <input ref={here} placeholder="how are you" />
    </div>
  );
};

export default App;

1) useRef( )를 사용해 Ref객체 만들기
2) 해당 객체를 활용한 작업 설정 .current.focus()
3) 만든 Ref객체를 선택하고 싶은 DOM에 ref 값으로 설정하기
-> Ref객체의 .current값은 선택한 DOM을 가리키게 된다!
+) useRef에 파라미터를 넣어주면, 이 값이 .current의 기본 값이 된다!



useEffect 란?

component가 마운트 / 언마운트 / 업데이트될 때,
할 작업을 선택하도록 하는 Hook함수
(외부 API를 요청하거나, 반복작업 / 작업예약 등에 쓰임)

기존의 class형에서는 세 가지의 각 상태들을 따로 관리해야 하는 불편함이 있었는데, useEffect를 사용하면 한 번에 관리할 수 있어 편리하다!


세 가지의 상태들을 기존의 메서드와 매칭하여 좀 더 알아보자면,

mount
: component가 처음 화면에서 보여질 때 (새로고침 시) (componentDidMount 메서드)

unmount
: component가 화면에서 사라질 때
(componentWillUnmount 메서드)

update
: 특정 props가 바뀌어 component가 업데이트될 때
(componentWillUpdate 메서드)


useEffect 사용하기

기본 사용법

useEffect(함수, [의존값 deps]);

useEffect(() => {
    mount 시 실행할 함수;
    return () => {unmount 시 실행할 내용}
}, [deps값]);

1) 먼저 mount 시 실행할 함수를 작성한다.
2) 반환 값에는 unmount 시 실행할 내용을 작성한다. (cleanup)
3) deps값에 특정 값을 넣으면, 해당 값이 업데이트될 때마다 useEffect에 작성한 함수가 재실행된다.

*빈배열로라도 두어야 useEffect에 작성한 함수가 처음 mount될 때만 실행됨(생략하면, 리렌더링 될 때마다 계속 함수를 불러오게 되니까)

*cleanup 함수
해당 effect가 더 이상 실행할 필요가 없을 때 청소하는 용도.
여기서 더 이상 실행할 필요가 없는 경우는 다음 두 가지이다.
1) dependancy(두 번째 인자로 넘기는 배열)가 바뀌어서 effect가 달라져야할 때 (이전 effect 청소)
2) 해당 component가 unmount 될 때

deps 정리!

정리하자면, deps가 [ ]일 때,
1) 컴포넌트가 처음 나타날 때에만, useEffect에 등록한 함수가 호출됨
2) return 값은 컴포넌트가 사라질 때 호출됨

deps에 특정 값을 넣으면,

1) 컴포넌트가 처음 마운트될 때 ( [ ] 일 때도 가능 )
2) 컴포넌트가 언마운트될 때 ( [ ] 일 때도 가능 )
3) 지정한 값이 바뀌기 직전에
4) 지정한 값(deps에 넣은 값)이 바뀔 때
호출이 된다.

=> useEffect안에서 사용하는 상태나 props 가 있다면, deps에 넣어주어야 하는게 규칙이다.

그래야 useEffect에 등록한 함수가 실행될 때, 최신 props 나 상태를 가르키기 때문이다.


useClick

useClick이라는 새로운 훅을 만들어서, 제목을 클릭할 때마다 콘솔 창에 특정 문구가 나타나도록 해보자.

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

const useClick = (onClick) => {
  // 예외처리
  if (typeof onClick !== "function") {
    return;
  }
  const element = useRef();
  useEffect(() => {
    // mount 시 실행 (click시, 받아온 onClick 함수 실행)
    if (element.current) {
      element.current.addEventListener("click", onClick);
    }
    // cleanup
    return () => {
      if (element.current) {
        element.current.removeEventListener("click", onClick);
      }
    };
  }, []);
  return element;
};

const App = () => {
  const sayHello = () => console.log("Hello");
  // useClick 훅에 sayHello 함수를 전달
  const title = useClick(sayHello);
  return (
    <div>
      // 바로 여기서 useClick을 사용할거다! (ref로 지정)
      <h1 ref={title}>Hello</h1>
    </div>
  );
};

export default App;
profile
울보 개발자(멍.. 하고 울어요)

2개의 댓글

comment-user-thumbnail
2024년 1월 20일

CompTIA Cybersecurity Analyst CS0-003 VCE are regarded to be very important for IT enthusiasts because they can provide several secure career opportunities to students along with many high paying roles in their respective sectors. CompTIA Cybersecurity Analyst (CySA+) Exam is not easy to pass in one try because CompTIA has developed it in a complex way.Technology and experience are also required for candidates to demonstrate and prepare for such a complicated exam.

답글 달기
comment-user-thumbnail
2024년 1월 20일

CompTIA Cybersecurity Analyst CS0-003 VCE are regarded to be very important for IT enthusiasts because they can provide several secure career opportunities to students along with many high paying roles in their respective sectors. CompTIA Cybersecurity Analyst (CySA+) Exam is not easy to pass in one try because CompTIA has developed it in a complex way.Technology and experience are also required for candidates to demonstrate and prepare for such a complicated exam.
CompTIA CS0-003 Exam Objectives

답글 달기