Web Dev/ELICE

56 :: Redux, 상태 관리, Context API

HJPlumtree 2022. 1. 11. 18:05

엘리스 SW 엔지니어 트랙 56일차

실시간 강의날

 

 

REDUX(리덕스)

리덕스는 자바스크립트에 포함된 기술이다

리액트에 포함된 기술이 아니다

 

소프트웨어 개발시 위험한게 복잡성이다

코드의 복잡성을 낮추기 위해 Redux를 사용한다

 

Single Source of Truth

단 하나의 객체에 어플리케이션이 사용하는 모든 데이터를 집어 넣는다

상태(state)는 그냥 객체다

 

데이터의 보안을 생각하기에

reducer, dispatcher 만 이용해서 데이터를 변경할 수 있다

직접 state 값을 바꾸지 못한다

 

데이터를 가져갈 때도 삼엄하다

getstate라는 함수를 이용해서 가져갈 수 있다

 

UNDO, REDO 쉽게 가능

 

 


store <안>

정보가 저장되는 곳

state가 저장된다

state를 직접 수정을 할 수 없다

 

  • getState: state값을 전해주는 함수(모든 state를 가져온다)
  • subscribe: state 값이 변경될 때 마다 render된다
  • dispatch: state을 변경(상태가 어떻게 바뀔 것인지 정의하는 함수)
  • reducer라는 함수: 현재 state와 action을 이용해서 새 state를 만든다

dispatch는 reducer를 호출,  현재 state와 action을 전해준다

reducer는 새로운 state를 만들어준다


store <밖>

  • render 함수들: state값을 가져와서(getState) UI 만든다

 

 

Redux 사용

1. store 생성

function reducer(oldState, action) {
	console.log("reducer");
}
const store = Redux.createStore(reducer);

createStore시 reducer를 넣어줘야하고, reducer가 1번 바로 실행된다

 

 

2. 현재 state를 가져오려면

getState() 사용

// getState
const state = store.getState()

 

 

3. dispatch로는 액션을 보내준다

액션이 결국 객체였구나

type에는 어떤 행동인지 알려주고, 뒤에는 저장될 값

// dispatch 
store.dispatch({type: 'CHANGE_COLOR', color: 'cyan'})

 

 

4. 받은 action을 reducer로 처리한다

위에서 받은 type을 이용해서 행동을 처리해서

새로운 state를 반환해준다

// reducer
function reducer(oldState, action) {
  console.log("reducer", oldState, action);
  if (oldState === undefined) {
  	return { color: "none" };
  }
  const newState = { ...oldState };
  if (action.type === "CHANGE_COLOR") {
  	newState.color = action.color;
  }
  return newState;
}

 

 

5. 이 변화를 감지하고 렌더링을 자동으로 하게 해주려면

subscribe를 사용한다

이 '함수'를 store를 구독하게 하는 것

그래서 변경이 있으면 고치게 한다

// subscribe
store.subscribe(함수)

 

 

Context API

props drilling 방지하기 위해 사용

글로벌 변수를 만드는 느낌

 

상태 관리가 아닌 데이터를 가져오기 위한 용이다

useState()와 함께 상태 관리를 한다

 

 

1. Conext API 사용하기 위하 준비

const TestContext = React.createContext();

 

2. Provider 컴포넌트에 값을 전해주면 전역적으로 값 사용 가능

// Provider
<TestContext.Provider value={content}>
	<FirstComponent></FirstComponent>
</TestContext.Provider>

 

3. data를 가져온다

// useContext()
function SecondComponent() {
  let data = useContext(TestContext);
  return <div>{data}</div>;
}

 

 

useReducer

useState랑 다른 방법으로 상태 관리

reducer: 현재 상태, '액션', 객체를 받아서 => 새로운 상태로 변환

 

// useReducer
const [state, dispatch] = useReducer(reducer, initialState);

 

 

참고 링크

Redux 생활 코딩

링크 => https://opentutorials.org/module/4078

 

Redux DevTools 크롬 확장

링크 => https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en

 

redux cdn

링크 => https://cdnjs.com/libraries/redux

'Web Dev > ELICE' 카테고리의 다른 글

58 :: React에서 Redux, 테스트  (0) 2022.01.13
57 :: 상태 관리, Flux Pattern, 상태 관리 Hooks  (0) 2022.01.12
55 :: Promise, async/await, 리액트 심화  (0) 2022.01.08
54 :: SPA, react-router,  (0) 2022.01.07
53 :: React Router, CORS  (0) 2022.01.06