관리 메뉴

Silver Library (Archived)

[2] react 와 JS 의 차이점을 제대로 알기. 본문

Face the fear, build the future/Laboratory

[2] react 와 JS 의 차이점을 제대로 알기.

Chesed Kim 2021. 10. 21. 21:07
반응형

개요:

'그 어떤 라이브러리도 추가 설치하지 말 것' 

이슈:

이 조건에 얽매여서 괜히 하루 종일 큰 의문을 가지게 함.

최종 결론은 setState 도 JS 에서 사용이 가능하다는 점. 이제 react 는 props 베이스라고 생각해야 할 정도.

하지만 이렇게 덮고 넘어가기에는 이제 위험하다는 생각이 들었습니다. 이걸로 이렇게 고뇌한게 세번째이므로.

 

React 와 JS 의 차이점은 무엇일까?

[React]

- JS 와 달리, 포멧(guideline)이 주어진다. 혼돈이 벌어지는 걸 막아줌. 개발.

- JS 와 달리, 가상돔(virtual DOM) 이 있다. 여기서 작업 하고 나면, 최종적으로 parsing 하듯이 HTML DOM 으로 표시.

- 필요할 때만 rendering 하므로 성능적으로 유리하다. 성능

- React 의 특징으로, component 단위 작성이 있음. (생산성과 유지 보수 용이)

 

Note:

1. Parse, compile, render 의 차이점

2. JS 에서 DOM 이란 무엇인가?

3. React 에서 가상돔(Virtual DOM) 이란 무엇인가?

4. JS 놔두고, 왜 굳이 React 를 사용하나?

Side. FE library 와 framework 가 등장하게 된 배경

5. React vs JS: 왜 프레임워크를 쓰는거지?

6. Props vs State [1], [2], [3], [문서]

Side. "State is a plain JavaScript object used by React to represent an information about the component's current situation. It's managed in the component (just like any variable declared in a function)."

 

자, 그럼 문제의 setState. 사실 이거, React.js 인 만큼, JS 에서 사용이 가능하다는 결론이 나왔다.

사용 예시를 보면, vanilla JS 로 component 구성 시 setState 뿐만 아니라 this 도 활용이 가능하다.

이제 의문이 깔끔하게 정리되었다.

// https://code-anthropoid.tistory.com/205
class Items extends Component{
    get filteredItems (){
        const {filterBy, items} = this.state
        return filterBy==='all' ? items : items.filter(({active})=>active===filterBy*1)
    }
    setEvent() {
        this.addEvent('click','.activate',({target})=>{
            const items = [...this.state.items]
            const targetIndex = target.closest('[data-index]').dataset.index*1
            this.setState({
                items: items.map(
                    item=>item.index!==targetIndex ?
                        item :
                        {...item, active: item.active ? 0 : 1}
                )
            })
        })

즉, reactjs 를 안 끼고 진행하더라도 아니더라도 이 API 구성 문제 자체가 '컴포넌트 구성' 이라는 결론이 나온다.

 

 

하나만...더 확실하게 짚고 가고싶다.

React 는 library 이며, library 와 framework 의 차이점은:

library performs specific, well-defined operations.
framework is a skeleton where the application defines the "meat" of the operation by filling out the skeleton. The skeleton still has code to link up the parts but the most important work is done by the application.
Examples of libraries: Network protocols, compression, image manipulation, string utilities, regular expression evaluation, math. Operations are self-contained.
Examples of frameworks: Web application system, Plug-in manager, GUI system. The framework defines the concept but the application defines the fundamental functionality that end-users care about.

대표적으로 짧게 알아두자면 이런 결과다. 참고로 Django 의 경우는 framework. React 는 library 다.


모든 의문이 풀렸다. 정말 react 없이도 별도로 외부에서 어떤 기묘한 방식으로 react 를 import 하는 상상을 초월하는 시험용 환경 구축 같은 최악의 시나리오 없이, 이 문제는 충분히 날 것 상태로도 API 출력 까지 구성이 가능 한 것이었다.

 

지금 현 시점에서 난관은, 저걸 어떻게 하지? 였었다. 하지만 지금이라면 해볼 만 하다.

이 말인 즉슨, 컴포넌트 구성으로 알아보면 된다는 힌트다.(JS 컴포넌트 만들기) [1] [2] [3]

 

how to make component in javascript?

Introduction to web APIs, what is web component?

 

웹 컴포넌트 | MDN

웹 컴포넌트는 그 기능을 나머지 코드로부터 캡슐화하여 재사용 가능한 커스텀 엘리먼트를 생성하고 웹 앱에서 활용할 수 있도록 해주는 다양한 기술들의 모음입니다.

developer.mozilla.org