React 기초 지식 / 환경 구축

uoayop·2021년 5월 14일
0

React

목록 보기
1/9
post-thumbnail

리액트 (React)

2013년에 처음 나온 리액트.

2019년에 가장 큰 변화가 생겼는데, 바로 클래스형 컴포넌트가 도태되고 Hooks와 함수형 컴포넌트가 등장했다는 점이다.

리액트는 어쩌다 만들어졌을까?

JS를 사용한 DOM 변형

DOM ? ⚓️
각 HTML element에 대한 정보를 갖고있는 JS의 객체

JS를 사용해서 HTML의 DOM에 접근하기 위해선, 브라우저의 DOM Selector API를 사용해서 특정 DOM을 선택한 뒤 특정 이벤트가 발생하면 변화를 주도록 해야한다.

const increaseBtn = document.getElementById('ID');
const num = document.getElementById('number');

increaseBtn.onclick() => {
  console.log('버튼이 눌렸어요');
  // parseInt : 문자열에서 10진수로 변화
  const current = parseInt(number.innerTest, 10);
  number.innerText = current + 1;
}

HTML 태그의 id, class를 사용해서 DOM을 선택한 뒤, 원하는 이벤트가 발생하면 DOM의 특정 속성을 변경시키는 방식이다.

이런 규칙은 사용자와 인터랙션이 많을 수록 코드의 양이 점점 들어나고, 관리가 어려워진다.

AngularJS

그래서 앵귤러 같은 프레임워크가 만들어졌다.
앵귤러는 JS의 특정값이 바뀌면,특정 DOM의 속성이 바뀌도록 연결을 해줘서 업데이트 하는 작업을 간소화 해준다.

React는?

리액트는 어떤 상태가 바뀌었을 때, 그 상태에 따라 DOM을 어떻게 업데이트할 지 규칙을 정하는게 아니라 아예 처음부터 모든 걸 새로 만들어서 보여준다.

따라서 업데이트를 어떻게 할 지 고민하지 않아도 된다. ( = 편한 개발. 그치만 과연 편할까? )

Virtual DOM

리액트에선 가상 돔을 이용해서 성능을 지킨다.

  • 브라우저에서 실제로 보여지는 DOM이 아니라, 메모리에 가상으로 존재한다.
  • 그냥 JS 객체이기 때문에, 작동 성능이 실제 DOM을 보여주는 것보다 훨씬 빠르다.

작동 원리

  1. 상태 업데이트가 된다.
  2. 업데이트가 필요한 UI를 메모리에 있는 Virtual DOM에 렌더링 한다.
  3. 실제 DOM과 Virtual DOM을 비교해서 차이점을 감지한다.
  4. 차이가 나는 부분을 실제 DOM에 반영(Patch) 해준다.

App.js에서 반환되는 HTML는 index.js의 id가 root인 <div> 안으로 들어간다. (컴포넌트로 렌더링 된다.)

개발자 도구로 소스 코드를 보면 id가 root인 태그의 안이 비어있는 걸 확인할 수 있는데, 이건 리액트가 가상돔을 이용해 렌더링을 해주기 때문이다!

리액트에선 정말 필요한 변화만 발생시킨다.
따라서 업데이트를 어떻게 할지 고민하지 않으면서도 빠른 성능을 지니게 된다.


컴포넌트

리액트에서는 UI를 컴포넌트에 담아서 선언한다.

input이 있을 때, output이 만들어지는 일종의 UI 조각이라고 이해하면 편하다.

  • HTML을 반환하는 함수라고 생각하자
const Hello = ({name}) => 
<div>
    Hello, {name} 
</div>

Webpack, babel?

리액트 프로젝트를 진행할 때, 컴포넌트를 여러가지 파일로 분리해서 저장하게 된다.
또 컴포넌트는 일반 JS가 아닌 JSX(Javascript XML)이라는 문법으로 작성하게 된다.

  • webpack : 여러가지 파일을 한개로 결합하기 위해 사용
  • babel : JSX를 비롯한 새로운 JS 문법들을 사용하기 위해 사용

작업 환경

설치해야 할 항목

  • node.js : 브라우저 환경이 아닌 곳에서도 JS를 실행할 수 있게 해주는 JS 런타임
  • yarn : 프로젝트에서 사용되는 라이브러리를 설치하고 해당 라이브러리들의 버전을 관리할 때 사용
  • vscode : 코드 에디터

프로젝트 만들기

$ npx create-react-app begin-react
# 프로젝트 만들기
$ cd begin-react

# react 실행
$ yarn start 또는 $ npm start

프로젝트 실행 시 발생한 에러

doyeon@192 begin-react % yarn start
yarn run v1.22.10
$ react-scripts start

There might be a problem with the project dependency tree.
It is likely not a bug in Create React App, but something you need to fix locally.

The react-scripts package provided by Create React App requires a dependency:

  "webpack-dev-server": "3.11.1"

Don't try to install it manually: your package manager does it automatically.
However, a different version of webpack-dev-server was detected higher up in the tree:

  /Users/doyeon/node_modules/webpack-dev-server (version: 3.11.2) 
  
  ..
  
  To fix the dependency tree, try following the steps below in the exact order:

  1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.
  2. Delete node_modules in your project folder.
  3. Remove "webpack-dev-server" from dependencies and/or devDependencies in the package.json file in your project folder.
  4. Run npm install or yarn, depending on the package manager you use.

In most cases, this should be enough to fix the problem.
If this has not helped, there are a few other things you can try:

  5. If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead.
     This may help because npm has known issues with package hoisting which may get resolved in future versions.

  6. Check if /Users/doyeon/node_modules/webpack-dev-server is outside your project directory.
     For example, you might have accidentally installed something in your home folder.

  7. Try running npm ls webpack-dev-server in your project folder.
     This will tell you which other package (apart from the expected react-scripts) installed webpack-dev-server.

If nothing else helps, add SKIP_PREFLIGHT_CHECK=true to an .env file in your project.
That would permanently disable this preflight check in case you want to proceed anyway.

P.S. We know this message is long but please read the steps above :-) We hope you find them helpful!

상위폴더 node_modules에 있는 의존성을 해결해주었다.

profile
slow and steady wins the race 🐢

0개의 댓글