티스토리 뷰

프로젝트를 하던 중 DOM을 참조해야 하는 일이 생겼는데 기존 자바스크립트에서 돔을 가져오는 getElementById와 리액트에서의 방식 ref 중 어떤것이 더 나은 방법인가 궁금해서 찾아보았다.

 

In general, refs is better than document.getElementById, because it is more in line with the rest of your react code.

 

일반적으로, ref가  document.getElementById보다 더 좋다. 왜냐면, 너의 리액트로된 나머지 코드들과 더 잘 맞기 때문이다.

In react, every component class can have multiple component instances.

리액트에서는 모든 컴포넌트가 여러개의 인스턴스를 가질 수 있다.


And as @Isuru points out in comments: using id is dangerous, because react does not prevent you to have multiple forms on 1 page, and then your DOM contains multiple inputs with same ID. And that is not allowed.

 

id를 사용하는건 위험하다. 왜냐면, 컴포넌트는 여러개의 인스턴스를 가질 수 있기 때문이다. id가 중복될수 있다는 말이다.

Another advantage to using refs, is that by design, you can only access the refs in the context where you define it. This forces you to use props and state (and possibly stores) if you need to access info outside of this context.

 

ref의 또다른 장점은, 내가 정한 스코프(컨텍스트)내에서만 ref에 접근 할 수 있다는것이다. 그렇게 함으로써 컴포넌트 스코프 바깥에 있는 정보를 사용하기 위해 props와 state(store에 저장된 state일지라도)를 사용하게끔 강제하는 장점이 생긴다.

 

-> ref를 사용함으로써 내가 참조하려고 하는 DOM을 컴포넌트 바깥에서는 접근하지 못하게 되면서, 코드를 좀 더 유지보수 하기 쉽게 만들어준다는 얘기인듯.


And this an advantage, because there is less/ no chance of you breaking your unidirectional data flow, which would make your code less manageable.

ref를 사용함으로써 단방향 데이터 흐름을 방해하지 않기 때문에 코드를 좀 더 유지보수하기 쉽게 만든다.

NB: In almost all cases, refs can be avoided altogether. It is a design principle for Netflix to use no refs, ever, as explained by Steve McGuire (Senior User Interface Engineer at Netflix) in this video from reactjs conf 2016 (9:58m into the video).

 

대부분의 경우에 ref를 사용하지 않고도 똑같은 코드를 구현 할 수 있다. 넷플릭스에서는 절대로 ref를 사용하지 않는다는 원칙을 만들고 지키고 있다고 한다.

 

결론

getElementById < ref 이나, ref도 최대한 사용하지 않는 것이 좋다.

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함