아름이의 개발로그

[공부 기록] JavaScript - react

|

1. React란?

React는 Facebook에서 제공하는 UI의 상태 관리를 효율적으로 해주는 JavaScript front-end library이다.

2. JSX (JavaScript XML)

JSX는 React를 사용하기 전에 알아둬야 할 문법이다. JSX는 작성한 React 컴포넌트를 화면에 보여주기 위해 사용한다.

class Hello extends Component {
  render() {
    return(
      <div>
        <h1>hello, world</h1>
      </div>
    )
  }
}

위의 return안에 있는 것이 JSX이다. React 컴포넌트는 반드시 JSX를 리턴해주어야 한다. 얼핏 보면 html처럼 보일 수 있지만 JSX는 JavaScript의 확장 문법이다.
JSX를 쓰지 않고도 React를 사용할 수 있지만 복잡하고 가독성이 떨어지는 단점이 있다. babel이라는 컴파일러가 JSX를 JavaScript로 해석하여준다.

2-1. JSX 문법

  1. 반드시 하나의 엘리먼트로 감싸야 한다.
    ```js // 잘못된 문법! class Hello extends Component { render() { return(

    hello

    walli

    ) } }

// 바른 문법! class Hello extends Component { render() { return( <div> <div> <h1>hello</h1> </div> <div> <h2>walli</h2> </div> </div> ) } }

2. JSX 내부에 자바스크립트 코드를 적용할 때는 {} (curly bracket) 안에 작성한다.  
```js
class App extends Component {
  render() {
    const name = 'walli';
    return (
      <div>
        hello {name}! // {} 안에 작성하기
      </div>
    )
  }
}
  1. JSX 내부에서는 if문을 사용할 수 없기 때문에 삼항연산자를 사용한다.
    class Hello extends Component {
      render() {
     return(
       <div>
         {
           (1 + 1 === 2) ? (<h1> 정답 </h1>) : (<h1> 탈락 </h1>)
         }
       </div>
     )
      }
    }
    
  2. 엘리먼트에 속성을 적용할 때는 camelCase 프로퍼티 명명 규칙을 사용한다. 클래스 이름을 적용하는 class같은 경우는 className을 사용한다.
    ```html
hello

// XXX

hello

// OOO


## 3. Element
element는 React 앱의 가장 작은 단위이다. element는 화면에 표시할 내용을 기술한다. 컴포넌트에서 `render`메소드 안에서 리턴되는 객체이다.

```js
const element = <h1>Hello, world</h1>;

4. Component & Data flow

Reactcomponent기반의 라이브러리이다. 아래의 그림에서 컵이 component라고 볼 수 있다.
React에서 데이터의 흐름은 단방향이다. 아래의 그림은 React의 데이터 흐름을 잘 표현해준다. 아래의 물은 위로 흐를 수 없기 때문에 항상 부모 컴포넌트에서 자식 컴포넌트로만 이동한다. react_data_flow

5. Props

propscomponent 사이를 타고 흐르는 data이다. 다시 말하면 상위 컴포넌트가 하위 컴포넌트에게 내려주는 데이터이다. propsimmutable하기 때문에 값을 읽을 수는 있지만 변경할 수는 없다. 아래의 그림으로 치면 흐르는 물이 props라고 볼 수 있다.
react_props

6. State

statecomponent가 갖는 상태이다. 객체의 형태로 컴포넌트 내에서 보관하고 관리한다. class-component에서만 사용할 수 있다. 값을 변경할 때는 항상 setState 메서드를 사용해야 한다. setState메서드를 통해야만 render 메서드가 실행되어 변경된 상태가 그려지기 때문이다.
아래의 그림으로 치면 컵에 고인 물이 state라고 볼 수 있다. react_state

7. Life cycle of React

React에는 componenet의 생성과 업데이트 그리고 삭제에 따라 Life cycle을 갖는다.
component가 생성될 때는 render가 완료된 후 componentDidMount 메서드가 실행된다. component가 업데이트 할 때는 render가 완료된 후 componentDidUpdate 메서드가 실행된다. component가 제거될 때는 componentWillUnmount 메서드가 실행된다.
프로그램의 복잡하게 변하는 상태와 데이터를 관리해야 하는 입장에서 봤을 때 데이터의 보장된 시점을 제공받을 수 있다는 점에서 Life cycle methods는 유용하다.
react_life_cycle

8. Event

React에서 event는 아래의 예시같이 작성할 수 있다.

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }
  
  return (
    <a herf="#" onClick={handleClick}>
      Click me
    </a>
  );
}

9. Functional-component VS Class-component

Functional-componentClass-component에서는 사용할 수 있는 statelife cycle methods를 사용할 수 없다.
하지만 아래와 같은 장점들이 있어서 꼭 필요한 경우가 아니면 Functional-component를 사용하는 것이 좋다.

  1. Functional-component는 가독성이 훨씬 좋고 테스트하기에 쉽다.
  2. 코드를 덜 쓸 수 있다.
  3. Functional-component를 사용하는 것은 setState 메소드 없이 컴포넌트의 state에 대해서 생각해볼 필요가 있기 때문에 presentational componentcontainer component를 분리하기 쉽다는 점에서 가장 좋은 연습이 될 수 있다.
  4. React 팀은 향후의 React 버전에서 Functional-component에 대한 성능 향상이 있을 수 있다고 언급했다.

Functional-componentClass-component는 아래와 같이 작성할 수 있다.

// functional-component
function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);
// class-component
class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

10. React를 써본 소감

UI를 작업할 때 상태를 관리하기 위한 수 많은 변수들을 만들어보고 그것들이 꼬여서 고생해본 적 있는 나로써는 React같은 모델을 왜 진작 몰랐나 싶고 React를 만든 사람은 분명 천재임이 분명하다고 생각했다.ㅋㅋ

출처
Codestates Immersive Course
https://ko.reactjs.org/docs/hello-world.html
http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
https://medium.com/@Zwenza/functional-vs-class-components-in-react-231e3fbd7108

Comments