본문 바로가기
웹(web)/프론트엔드-redux

redux 기초(data, modifier, action)

by 바코94 2021. 3. 10.

redux를 처음 접하면 굉장히 어려운 느낌이 든다. 구조가 전체적으로 이해가 안 가기 때문이다.

간단한 핵심 위주로 설명하고자 한다.

우선 redux를 쓰는 이유는 데이터를 관리하기 위함이다. 데이터를 관리하는 공간을 먼저 만드는 것이 시작이다.

const countModifier = (state = 0) => { return state;};
const countStore = createStore(countModifier); 

data를 관리하는 곳이 만들어졌다. createStore로 저장공간을 만들어야 하고 데이터를 리턴하는 함수인 modifier가 인자로 들어간다. countModifier의 리턴 값은 0이다. 

1. 데이터를 리턴하는 2. 함수 

1,2 를 만족하는 것이 redux에서 흔히 부르는 reducer이다. data를 수정하는 공간, 리듀서, data modifier 등 원하는 대로 부르면 된다. 

따라서, countStore에 있는 데이터들을 사용할 수 있게 된다. 지금은 저장공간에는 0이 들어 있다. 

 

그렇다면 이제 데이터를 수정하는 작업을 해보자. 1을 더하는 작업과 1을 빼는 작업이 필요하다고 해보자. 리듀서에서 해당 작업을 처리하는데 리턴하는 데이터가 바뀌었음을 볼 수 있다.

const countModifier = (state = 0, action) => { 
    if(action.type === 'ADD'){
    	return state + 1;
    }else{
    	return state;
    }
};
const countStore = createStore(countModifier);

countStore.dispatch({type: "ADD"})

dispatch라는 것을 사용하여 {type: "ADD"}를 인자로 주면 modifier에서 이를 이용해 state+1를 리턴한다.

"ADD"를 여러 번 dispatch하면 state의 값이 0->1->2 순으로 변경되게 된다. redux에서 데이터를 관리해주는 방식이다.

state = state + 1 을 해주는 것이 아니라 return state+1 을 해주면 우리가 원하는 것처럼 관리되는게 핵심이다.

 

결국 modifier(reducer)에서 하는 것은 dispatch의 인자인 action type에 따라 데이터를 수정해주는 역할을 하고 최종적으로 데이터를 리턴해주는 곳이다.

저장소이자 데이터를 변경할 수 있는 곳인 리듀서와 변경을 요청하는 dispatch로 데이터가 관리 되는 셈이다. 

 

countStore.getState()를 사용하면 1을 얻을 수 있다. 또한, counterStore.subscibe(callback) 해주면 counterStore의 데이터가 변경되었을 때 callback 함수를 호출해준다. 

 

const countModifier = (state = 0, action) => { 
    if(action.type === 'ADD'){
    	return state + 1;
    }else{
    	return state;
    }
};
const countStore = createStore(countModifier);

const onChange = () => { console.log("data changed") }; // ADD dispatch 될 때 마다 호출됨. 
countStore.subscribe(onChange)

countStore.dispatch({type: "ADD"})
countStore.dispatch({type: "ADD"})

console.log(countStore.getState()); // 2

 

'웹(web) > 프론트엔드-redux' 카테고리의 다른 글

redux를 쉽게 사용하기(reduxjs/toolkit)  (0) 2021.02.24