Redux

allofhyuk·2021년 4월 5일
0

React Hooks

  • 함수 컴포넌트에서 state와 life cycle를 연동할 수 있도록 해주는 함수
  • hooks는 하위 호환성을 가지고 있다.
  • class의 this.state
constructor() {
  this.state = {
  	count: 0
  }
}

와 달리 Hook에서의 state는 객체일 필요가 없다.

Hook의 두 가지 규칙

  1. 최상위에서만 Hook을 호출해야 한다. 반복문, 조건문, 중첩된 함수 내에서 Hook을 실행하면 안된다.
  2. React 함수 컴포넌트 내에서만 Hook을 호출해야 함. (Hook은 class 안에서 동작하지 않는다.)

Hook 이란?

  • 특별한 함수 이다.
import React, { useState } from 'react';

function Example() {
  // ...
}
  • useState는 state를 함수 컴포넌트 내에서 사용할 수 있게 해준다.
  • class component로 바꿔야 state를 추가 할 수 있었지만 Hook을 이용하면 함수 컴포넌트 내에서 state를 사용 할 수 있다.

Class this.state

class App extends React.component {
  constructor(props) {
    super(props)
    this.state = {
   	  count: 0
    };
  }
}
render() {
    return (
      <div> You clicked {this.state.count} times </div>
      <button onClick={() => this.setState({ count: this.state.count + 1 })} 		  </button>
    )
  }

State Hook

import React, { useState } from 'react'; // Hook을 React에서 가져온다.

function App() {
  const [count, setCount] = useState(초기값);
// Hook을 이용하여 state와 state를 갱신하는 함수 setCount 생성, count 값을 초기 값으로 초기화.
  return (
  <div> You clicked {count} times </div>
  <button onClick{() => setCount(count + 1)}> </button>
  // 버튼 클릭 시 setCount 함수 호출하여 state를 갱신
  // +1 된 count를 App 컴포넌트에 전달하며 리렌더링.
  )
}

Effect Hook

Classical component

  • 라이프 사이클 함수를 사용해야 함.
class App extends React.component {
  conponentDidmount() {
    // 컴포넌트 마운트 시 코드 실행.
  }
  conponentDidUpdate() {
    // App data 업데이트 시에 코드 실행.
  }
  conponentWillmount() {
    // 컴포넌트 언마운트 시 clean up
  }
}

Functional Component

import React, { useState, useEffect } from 'react';

function App() {
  const [count, setCount] = useState(0);
  useEffect(() => { 
    document.title = 'You clicked ${count} times'
  })
  // useEffect(effect) 
  
  return (
    <div> You clicked {count} times </div>
    <button onClick{() => setCount(count + 1)}> </button>
  )
}
  1. Clean-up을 이용하지 않는 Effects : 어떤 것도 반환하지 않는다.
  2. Clean-up을 이용하는 Effects : 함수를 반환한다.

Redux

  • 자바스크립트 앱에서 예측 가능한 상태 관리를 해주는 container
  • State는 Class component 내에서 관리
  • component간의 정보 공유를 할 시
    자식1 com -> 부모 com -> 자식2 com
    위와 같이 자식1 -> 자식2 로 직접 정보 전달이 불가! 그러므로 자식이 많아진다면 상태관리는 매우 복잡해진다.

이러한 복잡성을 줄여주기 위해 상태 관리 라이브러이인 Redux를 사용할 수 있다.

Redux의 3가지 원칙

  1. Single source of truth : 항상 같은 곳(store)에서 data를 가지고 온다.
  2. State is read-only : React에서 setState라는 method를 사용해야만 상태 변경이 가능했다.
    Redux에서는 Action이라는 객체를 통해 state를 변경할 수 있다.
  3. Changes are made with pure fucntions : 변경은 순수 함수로만 가능하다.(Reducer)

Flux architecture

  • Action -> Dispatcher -> Store -> View (단 방향 흐름)
    1. Store : 상태가 관리되는 오직 하나의 공간
    - component와 별개로 Store라는 공간이 있다.
    • Store안에 앱에서 필요한 state를 두고 component들에서 state정보가 필요할 때 store에 접근 하여 정보를 가져올 수 있다.
    1. Action : 자바스크립트 객체
      • 객체 내에 type을 비롯한 다양한 data가 담겨있다.
    • Store에 앱에 필요한 data를 운반하는 역할.
    1. Reducer : state와 Action을 이용해 다음 상태를 만들어 냄.
      • Action Dispatch -> Reducer -> Store(New state)
    • Action 객체가 Dispatch 메소드에 전달되고, Dispatch는 Reducer를 호출하여 새로운 state 값을 생성
      -> 데이터는 한 방향으로만 흘러야 한다!
    1. Dispatcher : 모든 데이터 흐름을 관리하는 중앙 허브

Redux의 장점

  1. 상태를 예측 가능하게 만들어 준다.
  2. 유지보수 용이.
  3. 디버깅에 유리하다. (Action과 state log 기록 시)
  4. 순수함수를 사용하기 때문에 테스트를 붙이기 쉽다.

0개의 댓글