[Redux] createStore๋ฅผ ํด๋ณด์
Redux๋ฅผ ์์ํ๋ ค๋ฉด ๋ญ๋ถํฐ ํด์ผํ ๊น?
๋ฐ๋ก ์ํ๋ฅผ ๊ด๋ฆฌํ๋ ์ค์ง ํ๋์ ๊ณต๊ฐ์ธ store๋ฅผ ๋ง๋ค์ด์ผํ๋ค.
์ต๊ทผ ๋ฉด์ ๊ณผ์ ์์ ๋ผ์ด๋ธ์ฝ๋ฉ์ผ๋ก Redux์ store๋ฅผ ๋ง๋๋ ํจ์๋ฅผ ๊ตฌํํ๋ผ๋ ๋ฌธ์ ๊ฐ ๋์๋ค.
์์ด๊ณ .. ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ๋ก๋ํด์ ์ฌ์ฉํ ์ค๋ง ์์์ง..
์์ ๋์๊ฐ๋ ๋ฉ์ปค๋์ฆ์ ์์ธํ ์๋ ค๊ณ ํ์ง์์๋ ๋ด ์ง๋ ๊ณผ์ค๊ฐ ๋จธ๋ฆฟ์์์ ์ข๋ฅด๋ฅต ํ๋ฌ๊ฐ๋ค.
๋ค.. ๊ทธ๋ ๊ฒ ์๋ฌด๊ฒ๋ ํ์ง ๋ชปํ ์ฑ ๋ฉด์ ์ ๋์ด๋ฌ๊ณ , ์์ฝ์ง๋ง ์ด์ฉ๊ฒ ๋.
์ง๊ธ๋ถํฐ ํด๋ณด์.
Store
์ฐ์ , store๋ ์ ์ญ ์ํ๋ฅผ ๊ฐ์ง๋ค.
const store = {
getState,
subscribe,
dispatch,
}
๊ทธ๋ฆฌ๊ณ ์ ์ญ ์ํ๋ฅผ ์กฐํํ๋ getState, ์์ ์ด ๊ด๋ฆฌํ๊ณ ์๋ ์ ์ญ ์ํ๋ฅผ ๊ตฌ๋ (์ํ๊ฐ ๋ณ๊ฒฝ๋๋ฉด ๋ณ๊ฒฝ๋์์์ ์ ๋ฌ)ํ ์ ์๋ subscribe, action์ ์ธ์๋ก ๋ฐ๊ณ reducer๋ฅผ ํตํด ์ ์ญ ์ํ๋ฅผ ๋ณ๊ฒฝ์ํค๊ณ ๋์ ๋ณ๊ฒฝ์ฌํญ์ ๊ตฌ๋ ์๋ค์๊ฒ ์ ๋ฌํ๋ dispatch API๋ฅผ ์ ๊ณตํ๋ค.
CreateStore
createStore๋ ํจ์์ ์ธ์๋ก reducer๋ฅผ ๋ฐ๋๋ฐ ์ด reducer๋ state๋ฅผ ๋ณ๊ฒฝ์ํค๋ ์ญํ ์ ํ๋ค.
store๋ ์ค๋ก์ง ์์ ํจ์์ธ reducer๋ฅผ ํตํด state๋ฅผ ๋ณ๊ฒฝ์ํฌ ์ ์๋ค.
function createStore(reducer){
function getState(){}
function subscribe(){}
function dispatch(){}
const store = {
getState,
subscribe,
dispatch,
}
return store;
}
getState
function createStore(reducer) {
let state = undefined;
function getState() {
return state;
}
...
}
state๋ฅผ ์ง์ญ๋ณ์๋ก ๊ฐ์ง๊ณ getState๋ฅผ ํตํด ์ ์ญ ์ํ๋ฅผ ์กฐํํ๋ค.
createStore๊ฐ ํด๋ก์ ์ด๊ธฐ๋๋ฌธ์ getState๋ ๊ณ์ํด์ state๋ฅผ ์ฐธ์กฐํ ์ ์๋ค.
subscribe
์ ์ญ ์ํ๋ฅผ ๊ตฌ๋ ํ ์ ์๊ฒ ํด์ฃผ๋ ๋ฉ์๋๋ก,
๊ตฌ๋ ์ ๋ฐฐ์ด์ ๋ง๋ค์ด ๊ตฌ๋ ์๋ ๋ฑ๋กํด์ฃผ๊ณ ๊ตฌ๋ ์ ํด์ ํ๋ ์๋ ์ญ์ ์์ผ์ฃผ๋ฉด ๋๋ค.
๊ทธ๋ฌ๋ฉด store๋ ๊ตฌ๋ ์ ๋ฐฐ์ด์ ์ํํ๋ฉด์ state๊ฐ ๋ณ๊ฒฝ๋์์์ ์๋ฆฐ๋ค.
function createStore(reducer){
let state = undefined;
//๊ตฌ๋
์ ๋ฐฐ์ด
const subscribers = [];
function subscribe(subscriber){
//๊ตฌ๋
์ ๋ฑ๋ก
subscribers.push(subscriber);
//๊ตฌ๋
ํด์
return unsubscribe(){
//๊ตฌ๋
์ ์๊ธฐ ์์ ์ ์ญ์
subscribers.splice(subscribers.indexOf(subscriber), 1);
}
}
...
}
dispatch
dispatch๋ action์ ์ ๋ฌ๋ฐ์ reducer๋ฅผ ํตํด ์ํ๋ฅผ ๋ณ๊ฒฝ์ํค๊ณ ๋ณ๊ฒฝ์ฌํญ์ ๊ตฌ๋ ์๋ค์๊ฒ ์ ๋ฌํ๋ค.
๊ทธ๋ฆฌ๊ณ ๋ค์ action์ ๋ฐํํด ๋ค์ dispatch ํจ์๊ฐ action์ ๋ฐ์ ์ ์๋๋ก ํ๋ค.
function createStore(reducer){
let state = undefined;
const subscribers = [];
function dispatch(action){
//๋ณ๊ฒฝ๋ ์ํ ์๋ก ๋ฑ๋ก
state = reducer(state, action);
//๊ตฌ๋
์๋ค์๊ฒ ์ ๋ฌ?
subscribers.forEach(subscriber => subscriber())
return action;
}
...
}
์ฐธ์กฐ