코규리
article thumbnail

프로젝트에서 필요했던 react 관련 내용을 정리합니다

 

 

Redux

: js App을 위한 state container (react, augular, jQuery, vanillaJS등의 framework와도 작동)

: action에 반응하여 상태를 변경함 (UI 상태에 대한 함수 기술 framework, 즉 리액트와 잘 어울림)


1. React에서 Redux가 필요한 이유


  • react에서 Component와 Application은 각각 다음의 state를 가진다
    • Component: local state, Application: global state
  • 프로젝트 규모가 커지며 Component의 수가 늘어나면 local state의 전달이 어렵다
    • data전달시 필요없는 data의 흐름이 생긴다
    • data전달이 잘 안되면 중간에 위치한 모든 Component에서 문제점을 일일이 찾아야 한다
  • 일반적인 로그인 기능 등에서 global state를 모든 Component에 유지하기 어렵다
    • 유저의 인증정보를 모든 Component에 props로 계속 전달해야하는데 이 절차가 복잡해진다
  • redux를 사용하면
    • 하나의 store를 통해 global state를 포함한 모든 state를 저장/유지 가능해진다
    • 원하는 Component로만 data의 전달이 가능하게 된다

 

2. Redux의 3가지 개념


  • Action: 어플리케이셔의 store, 즉 저장소로 data를 보내는 방법
    • view에 정의된 액션 호출시, action creates이 해당 Application의 state를 변경해줌
  • Reducers: action에서 정의한 행위에 대하여, 그 결과 어플리케이션의 상태가 어떻게 바뀌는지 얘기함
  • Store: action(무엇이 일어날 지)와 reducer(어떤 변화가 일어날 지)를 저장하는 단 하나의 객체

 

 

reducer를 위한 기본 절차 따라해보기


1.  디렉토리 구성하기


store
    -actions
        -index.js
    -reducers
        -index.js
        -aReducer.js
        -bReducer.js
        -cReducer.js

 

2. reducers/reducs.js 작성하기


aReducer, bReducer, cReducer 각각의 리듀서를 작성했다고 치자. export도 파일명처럼 해줬다고 치자.

 

3. reducers/index.js에서 combine시키기


  • redux모듈의 counterReducer함수를 사용해야한다
  • 예시코드
import aReducer from './aReducer'
import bReducer from './bReducer'
import {combineReducers} from 'redux'

const rootReducer = combineReducers({
	a: aReducer, //이름을 붙이지 않을 거라면 aReducer만 해도 됨
	b: bReducer 
)}

export default rootReducer;

 

4. actions/index.js 에서 action 정의하기


  • reducer의 인자가 되는 actions을 정의한다
  • 예시코드
export const increment = () => {
	return {
		type: 'INCREMENT'  //type은 그저 명명일 뿐, 다른 name으로 사용해도 된다
	}
}

export const decrement = () => {
	return {
		type: 'DECREMENT'
	}
}

 

5. src/index.js 에서 store디렉토리 적용하기


  • reducer를 import함
    • store를 만듦 > combined한 reducer를 import함
      • global states App과 연결하기 위해 Provider를 import함
  • 예시코드
import React from 'react';
import ReeactDOM from 'react-om',
import App from './App';
import { createStore} from 'redux';
import allReducers from './reducers';
import { Provider} from 'react-redux';

// createStroe의 두 번째인자: redux에서 제공하는 dexTool을 가져온 것이다(extention)
const store = createStrore(allReducers, window.__REDUX_DEVOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

ReactDOM.render(
	<Provider store={store}>
		<App />
	</Provider>,
	document.getElementById('root')
);

 

 

 


참고링크

 

[react] redux로 상태 관리하기 #시작하며 2

시작하며 1편에서 다루었던 글에서는 redux-actions 를 사용하는데, redux 와 react-redux 모듈로도 충분하지 않을까 싶었다. 패턴 역시 좀 더 직관적으로 이해할 수 있으면 좋을 것 같아서 즐겨보는 유튜

uiyoji-journal.tistory.com

 

 

 

React에 Redux 적용하기(1)

리덕스(Redux)란?

medium.com