IT 기초/Application

[Application] React

데이터 세상 2021. 12. 31. 14:49

React

React는 framework이 아니라 library이다.

[React 공식 문서]

 

Create a New React App – React

A JavaScript library for building user interfaces

reactjs.org

참고 사이트: https://react.vlpt.us/basic/01-concept.html

 

React는 javascript library의 하나로 사용자 인터페이스를 만들기 위해 사용된다.

페이스북과 개별 개발자 및 기업들 공통체에 의해 유지보수된다.

 

React Main Concept

React는 어떠한 상태가 바뀌었을 떄, 그 상태에 따라 DOM을 어떻게 업데이트할지 규칙을 정하는 것이 아니라,

아예 다 날려버리고 처음부터 모든 걸 새로 만들어서 보여준다면 어떨까에서 시작되었다.

<html>
<body>
 <h1 id="group"> Test </h1>
 <button>Change Name</button>
<body>
</html>

위와 같은 페이지가 있을 대 "Change Name" button을 click시 h1 value가 "Test2"로 변경되는 기능을 구현하고 싶을 때

  • 기존 방식은 id가 name인 h1 DOM node를 찾아서 value를 "Test2"로 update 한다.
  • React는 전체 body 내용을 삭제하고 하기와 같이 <h1 id="group">Test2</h1> 이라는 component를 포함한 새로운 body를 생성한다.

하지만, 정말로 동적인 UI 를 보여주기 위해서 모든걸 다 날려버리고 모든걸 새로 만들게 된다면, 속도가 굉장히 느릴 것이다. 하지만, 리액트에서는 Virtual DOM 이라는 것을 사용해서 이를 가능케한다.

 

Virtual DOM

React에서 값의 변경이 생겼을 때 코드는 실제 DOM을 control하는 것이 아니라 Virtual DOM을 control한다.

특정 React Component의 값이 변경 되었을 때 Virtual Dom에서 해당 Component를 삭제하고 새로운 값이 담긴 Component를 생성한다.

Virual DOM rendering이 완료되면 React 내부에서 Virtual DOM과 실제 DOM 값을 빠르게 비교하여 변경된 부분만 update 하게 된다.

 

React 환경 설정

대부분 react project는 React Official Site에서 제공하는 create-react-app tool를 사용하여 생성

https://reactjs.org/docs/create-a-new-react-app.html

npx create-react-app my-app
cd my-app
npm start

 

JSX

https://ko.reactjs.org/docs/introducing-jsx.html

https://reactjs.org/docs/jsx-in-depth.html

const element = <h1>Hello, world!</h1>;
  • JavaScript를 확장한 문법
  • React element를 생성

React에서는 본질적으로 렌더링 로직이 UI 로직(이벤트가 처리되는 방식, 시간에 따라 state가 변하는 방식, 화면에 표시하기 위해 데이터가 준비되는 방식 등)과 연결된다.

 

React는 JSX 사용이 필수가 아니지만, 대부분의 사람은 JavaScript 코드 안에서 UI 관련 작업을 할 때 시각적으로 더 도움이 된다고 생각합니다. 또한 React가 더욱 도움이 되는 에러 및 경고 메시지를 표시할 수 있게 해줍니다.

 

Class based React

React Component

class Test extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            name: 'none'
        }
        this.handleOnClick = this.handleOnClick.bind(this);
    }
    handleOnClick () {
        var newState = {...this.state};
        newState.name = 'jichun';
        this.setState(newState);
    }
    render () {
        const {buttonName} = this.props;
        return (
            <h1>{this.state.name}</h1>
            <button onClick={this.handleOnClick}>
                {buttonName}
            </button>
        );
    }
}

 

동작 방식

모든 React Component는 state, props 값과 render() 함수가 존재한다.

  • render: 해당 component를 virtual dom에 render하고 최종적으로 dom node에 rendering 하게됨.
  • state: 해당 component의 상태, 해당 값이 변경되면 React Component의 update lifecycle이 실행 됨, 간단하게 render 함수가 실행된다고 생각하면 됨.
  • props: Parent component에서 전달해오는 값들이다.

즉 render () 함수가 실행되면 실제 page가 update 된다.

render 함수는 개발자가 직접적으로 호출 할수 없고 Component의 state값이 변경 시 자동으로 호출된다.

즉 state값 변경으로 component의 update를 control 할 수 있다.

 

setState 함수를 이용하여 state값을 변경해야 React Component의 render()가 실행 된다.

  • this.state.comment = 'Hello'; N
  • this.setState({comment: "Hello"}); Y

setState() 함수를 call 할 시 전달한 값은 현재 state값에 merge가 된다(이전 버전과 달라진 점).

constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: ['bbb']
    };
  }
 
this.setState({
   posts: ['AAA']
});
 
state값은 하기와 같이 변경 됨.
this.state = {
    posts: ['AAA'],
    comments: ['bbb']
}
 

 

React에서 data는 Parent => Child 방향으로 전달 됨.

  • Child에서 Parent에 data를 전달하려면 Parent에서 callback 함수를 child에 넘겨주는 방법으로 가능 함.

 

React Lifecycle

https://reactjs.org/docs/react-component.html

반응형

'IT 기초 > Application' 카테고리의 다른 글

[Application] Node.js  (0) 2021.12.31
[Application] Spring  (0) 2021.12.31
[Application] Web Application Framework  (0) 2021.12.29
CI/CD  (0) 2021.12.27
3 Tier  (0) 2021.12.27