🕹 리액트 DOM 컨트롤
리액트 앱은 대부분 리액트에 의해 컨트롤되지만 예외인 상황이 있다. 리액트는 virtualDOM을 가지고 동작하기 때문에 RealDOM 요소에 접근하거나 조작해야할 경우 이는 리액트가 할 수 없는 일이다.
이러한 일을 리액트 사이드 이펙트라고 부른다. 흔히들 사이드 이펙트를 부작용이라고 오인하는 경우가 있지만 여기서는 순수하지 않거나 역할에 맞는 일을 하지 않는 경우를 말한다.
사이드 이펙트를 처리하기 위해서는 다음과 같은 React API를 사용하여야한다.
- ref(참조 설정)
- 값이 변경되어도 리액트가 재렌더링하지 않는다.
- callback ref(ref 속성에 연결된 함수)
- React.createRef(참조 객체 생성)
- React.forwardRef(참조 객체 전달)
- 범용적으로 누구나 사용할 수 있는 컴포넌트를 만들기 위해서 꼭 필요하다.
- 외부 컴포넌트가 내부 컴포넌트를 전달받아서 컴포넌트를 내보낸다.
- domRef를 통해서 전달할 수도 있다.
💭 예시
컴포넌트 생성 시점에 이벤트를 구독한 경우, 컴포넌트 제거 시점에 구독한 이벤트를 취소해야한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| export class TiltCard extends React.Component { tiltRef = React.createRef(null);
#cardDomElement = null;
componentDidMount() { this.#cardDomElement = this.tiltRef.current; VanillaTilt.init(this.#cardDomElement);
this.#cardDomElement.addEventListener( "tiltChange", this.handleChangeTilt.bind(this) ); }
componentWillUnmount() { this.#cardDomElement.vanillaTilt.destroy();
this.#cardDomElement.removeEventListener( "tiltChange", this.handleChangeTilt.bind(this) ); }
render() { const { children } = this.props;
return ( <div ref={this.tiltRef} className="tiltCard"> {children} </div> ); } }
|
- tiltRef에 DOM 요소를 저장하기 위해 ref를 생성하였다.
- tiltRef DOM 요소 얻기 위해 “current” 프로퍼티에 접근하였다.
- tiltRef DOM 요소에 컴포넌트 생성주기에 맞게 이벤트를 등록하고 제거해주었고 ref를 참조하도록 설정해주었다.