References

https://ko.redux.js.org/

https://hanamon.kr/redux란-리덕스-상태-관리-라이브러리/

 

 

Redux의 정의

ReduxReact에서 사용되는 상태 관리 라이브러리이다.

Vuex(Vue) 처럼 전역적인 상태 관리 기능을 제공한다.

 

 

Redux의 상태 관리 구조

Redux를 통한 상태 관리의 흐름은 Action, Reducer, Store로 이루어지는데 세부 사항은 다음과 같다.

 

Action

상태 관리에 필요한 데이터들을 운반 한다.

const actionSample = (newData) => {
    return {
        type: 'ACTION_CHANGE',
        payload: newData
    }	
}

 

Reducer

Action에 의해 운반하는 데이터 상태를 업데이트 한다.

const reducerSample = (state = sampleData, action) => {
    switch(action.type) {
        case 'ACTION_CHANGE':
            return Object.assign({}, state, { ...state, name: action.payload });
            break;
        default:
            return state;
    }
}

 

Store

상태 관리를 하는 유일한 공간으로 각 컴포넌트 마다 필요한 정보가 있을때 접근한다.

// store 기능 불러오기
const { createStore } = require('redux');
const store = createStore(reducerSample);

// 업데이트 전
console.log(store.getState());

// dispatch 함수를 통해 action을 실행한다
store.dispatch(actionSample('하나몬'));

// 업데이트 후
console.log(store.getState());

/**
store.getState() : 현재 store에 저장된 상태를 불러온다
store.dispatch('액션') : 해당 action으로 상태를 업데이트(Reducer) 한다
store.subscribe(이벤트) : 작업이 store에 전달될 때마다 호출된다
replaceReducer('다음 리듀서') : store에서 사용하는 reducer를 바꾼다. (별도 API 사용)
*/

 

 

Redux의 기본 원칙

Single source of truth

구현 과정에서 지정된 소스는 한 곳에서만 가져온다.

즉, 스토어라는 저장 공간을 통해 출처가 보장된 데이터 만을 가져온다.

 

State is read-only

상태 관리에 있어서 데이터를 외부 참조할 경우 이를 따로 변경하지 말것.

이는, Redux에서 제공하는 Actions라는 객체를 통해서만 상태를 변경한다.

 

Changes are made with pure functions

상태 관리를 할 때 업데이트순수 함수로만 가능하다.

이는 Redux의 데이터 흐름과 연관되는데 단방향으로만 흐를수 있게 제작되었기 때문이다.

https://i0.wp.com/hanamon.kr/wp-content/uploads/2021/07/ 리덕스-상태관리-단계.png?w=919&ssl=1

'Self-Study > React' 카테고리의 다른 글

[React] React의 라이프사이클  (0) 2022.10.13
[React] Next.js의 기본 개념  (0) 2022.10.06
[React] Router  (0) 2022.05.05
[React] useEffect  (0) 2022.05.05
[React] state  (0) 2022.04.17