성능 문제
위의 문제를 Redux 등의 상태 관리 라이브러리가 해결할 수 있다. (MobX, recoil 등)
리덕스는 앱에 있는 '하나'의 중앙 데이터(상태) 저장소
컴포넌트는 절대 저장된 데이터를 직접 조작하지 않음. 데이터는 단방향으로 흐름.
컴포넌트 <-> 리듀서 함수를 연결하는 것이 action임.
1) 컴포넌트가 action을 dispatch함.
2) 리덕스는 action을 reducer로 전달.
3) reducer는 action에 대한 작업을 읽고 수행하게 됨.
const {configureStore} = require('@reduxjs/toolkit');
Reducer 설정 (action type에 맞는 동작 설정)
const counter = (state = {counter: 0}, action) => {
// reducer는 항상 두개의 매개변수(기존의 상태, 발송된 액션)를 받음.
// 항상 새로운 state 객체를 리턴해야만 한다. 부수적인 메서드를 추가하면 안되며, 순수함수여야만 함.
if (action.type === 'INCREMENT') {
return {
counter: state.counter + 1,
};
}
if (action.type === 'DECREMENT') {
return {
counter: state.counter - 1,
};
}
return state;
};
앱에 존재할 한 개의 저장소(store) 생성
const store = configureStore({
reducer: counter, // 사용할 리듀서
});
컴포넌트가 store를 구독하는 방법
const counterSubscriber = () => {
// getState는 store에서 최신 state의 스냅샷을 제공함.
const latestState = store.getState();
console.log(latestState);
};
store.subscribe(counterSubscriber);
// counterSubscriber 함수를 취해서 store와 연결함.
// 상태 변화가 발생할 떄마다 counterSubscriber 호출
store.dispatch({type: 'INCREMENT'}); // 1
store.dispatch({type: 'INCREMENT'}); // 2
store.dispatch({type: 'DECREMENT'}); // 1