0917 TIL Redux

냐하호후·2021년 9월 17일
0

TIL

목록 보기
43/101

🙆‍♀️상태 관리 라이브러리가 왜 필요한지 이해할 수 있다.
🙆‍♀️Redux (혹은 Flux Pattern)에서 사용하는 Action, Reducer 그리고 Store의 의미와 특징을 이해할 수 있다.
🙆‍♀️Redux의 3가지 원칙이 무엇이며, 주요 개념과 어떻게 연결되는지 이해할 수 있다.
🙆‍♀️Presentational 컴포넌트와 Container 컴포넌트의 개념을 이해할 수 있다.
🙆‍♀️Redux hooks(useSelector, useDispatch)를 사용해 store 를 업데이트할 수 있다.

요약: action객체는 dispatch 메서드에 전달되고 dispatch 메서드는 reducer를 호출해서 새로운 state 생성

Redux 작동원리

action은 store의 state를 어떻게 바꿀지 적어둔 정보가 담긴 객체이다.
action객체는 정보를 dispatch메소드로 reducer에 전달한다. reducer가 type을 체크하고 store의 state를 새로운 state로 만든다.

Redux의 장점

  1. Redux는 순수함수라서 상태를 예측 가능하게 만들어준다.

  2. 유지보수

  3. 디버깅에 유리하다
    redux를 쓰지 않았을 때 state에 오류가 생기면 수십개의 컴포넌트를 다 뒤져봐야한다.
    redux를 사용하면 store.js만 보면 된다.

  4. 테스트를 붙이기 쉽다.

Redux 사용법

state를 보관할 수 있다. ex) store.js
props없이 store에 보관해둔 state를 어디서든 꺼내 쓸 수 있다.

밑의 코드는 Redux 설치/ 세팅방법일 뿐 이해할 필요가 없다.

//index.js
import {Provider} from 'react-redux';
import {createStore} from 'redux'

const 체중 = 100 //state 마음대로 보관 가능

function reducer(state = 체중,action){
return state
}

let store = createStore(reducer)

ReactDOM.render(
<React.StrictMode>
  <Provider store = {store}>
    <App/>
  </Provider>
</React.StrictMode>
)

컴포넌트 파일에서 store(여기서는 index.js)에 있던 체중이라는 변수를 쓸 수 있다.

//App.js
import {useSelector} from 'react-redux'

function App() {
  
 const 꺼내온거 = useSelector((state) => state )
 //리덕스 라이브러리 사용법
 
 return(
   <div className = "App">
     <p>당신의 몸무게 : {꺼내온거}</p>
     </div>
   )
}

export default App;

다시 index.js 파일을 보자.state의 수정방법을 미리 작성해둔다. 다른 컴포넌트들에서는 state 수정을 요청만 할 뿐이지 컴포넌트에서 직접 바꾸지 않는다.

//index.js
import {Provider} from 'react-redux';
import {createStore} from 'redux'

const 체중 = 100 //state 마음대로 보관 가능

function reducer(state = 체중,action){
if(action.type === '증가'){
  state++;
  return state
 } else if(action.type === '감소'){
  state--;
   return state
 } else {
  return state
 }
}

let store = createStore(reducer)

ReactDOM.render(
<React.StrictMode>
  <Provider store = {store}>
    <App/>
  </Provider>
</React.StrictMode>
)

컴포넌트에서 state 수정을 요청하려면 dispatch를 사용한다.

//App.js
import {useSelector,useDispatch} from 'react-redux'

function App() {
  
 const 꺼내온거 = useSelector((state) => state )
 //리덕스 라이브러리 사용법
 const dispatch = useDispatch()
 
 return(
   <div className = "App">
     <p>당신의 몸무게 : {꺼내온거}</p>
     <button onClick = {()=>{ dispatch({type:'증가'}) }}더하기</button>
     </div>
   )
}

export default App;

참고

코딩애플 유튜브
스프린트 분석

profile
DONE is better than PERFECT

0개의 댓글