Redux Toolkit은 Redux 로직을 작성하기 위해 저희가 공식적으로 추천하는 방법입니다. RTK는 Redux 앱을 만들기에 필수적으로 여기는 패키지와 함수들을 포함합니다. 대부분의 Redux 작업을 단순화하고, 흔한 실수를 방지하며, Redux 앱을 만들기
쉽게 해주는 모범 사례를 통해 만들어졌습니다.
Can I use Redux without Redux toolkit?
: Note that you are not required to use Redux Toolkit to use Redux. There are many existing applications that use other Redux wrapper libraries, or write all Redux logic "by hand", and if you still prefer to use a different approach, go ahead! However, we strongly recommend using Redux Toolkit for all Redux apps
: JS앱을 위한 예측 가능한 상태 컨테이너.
'액션'이라고 불리는 이벤트들을 사용해 애플리케이션의 상태를 관리하고 업데이트하는 패턴이자 도구. 애플리케이션 전역에서 필요한 상태들을 관리하기 위해 중앙화된 store(저장소?) 역할을 한다. 상태들이 예측가능한 상황에서만 업데이트되도록 보장한다.
: 애플리케이션의 여러 부분에서 필요한 상태들을 전역적으로 관리할 수 있다. 언제, 어디서, 왜, 어떻게 상태가 업데이트되는지 파악하기 용이.
: 리덕스의 단점으로는, 학습 내용 증가, 길어지는 코드, indirection 추가 (참조, In computer programming, an indirection (also called a reference) is a way of referring to something using a name, reference, or container instead of the value itself), 따라야 하는 제한 사항들을 들 수 있는데,
이러한 리덕스가 유용하게 사용되는 경우는 다음과 같다.
https://ko.redux.js.org/tutorials/essentials/part-1-overview-concepts
Redux는 자바스크립트 애플리케이션에서 예측 가능한 상태 관리를 제공하는 라이브러리입니다. 주로 React와 함께 사용되지만, React에 종속적인 것은 아닙니다. Redux의 주요 개념들과 이들의 역할, 사용법을 정리해보면 다음과 같습니다:
1. Store (스토어)
import { createStore } from 'redux';
const store = createStore(reducer);
createStore 함수는 리듀서를 인자로 받아 스토어를 생성합니다. 이 스토어를 통해 상태를 관리할 수 있습니다.
2. Actions (액션)
const increment = () => {
return {
type: 'INCREMENT'
};
};
여기서 increment는 액션 생성자입니다. type: 'INCREMENT'는 액션의 종류를 나타내는 문자열입니다.
3. Reducers (리듀서)
const counterReducer = (state = { count: 0 }, action) => {
switch(action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
};
여기서 counterReducer는 상태 관리 로직을 포함한 함수로, 액션의 타입에 따라 상태가 변하게 됩니다.
4. Dispatch (디스패치)
store.dispatch({ type: 'INCREMENT' });
store.dispatch()를 사용하여 액션을 스토어에 전달하면, 리듀서가 호출되어 상태를 업데이트합니다.
5. Selectors (셀렉터)
const selectCount = (state) => state.count;
const currentCount = selectCount(store.getState());
위 예시에서 selectCount는 상태 객체에서 count 값을 추출하는 셀렉터입니다.
6. Middleware (미들웨어)
const loggerMiddleware = store => next => action => {
console.log('dispatching', action);
let result = next(action);
console.log('next state', store.getState());
return result;
};
const store = createStore(reducer, applyMiddleware(loggerMiddleware));
이 예시에서 loggerMiddleware는 액션이 디스패치될 때마다 이를 콘솔에 출력해주는 역할을 합니다.
7. Combine Reducers (리듀서 합치기)
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
counter: counterReducer,
user: userReducer
});
const store = createStore(rootReducer);
위 코드에서 counterReducer와 userReducer를 하나의 rootReducer로 합쳐서 스토어에 전달하고 있습니다.
8. Redux Thunk
const fetchData = () => {
return (dispatch) => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => dispatch({ type: 'FETCH_SUCCESS', payload: data }));
};
};
이 예시에서 fetchData는 API에서 데이터를 가져와 성공적으로 받아오면 FETCH_SUCCESS 액션을 디스패치합니다.
9. Redux DevTools
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
DevTools를 활성화하면 상태와 액션을 시간 순으로 확인하고, 시간을 되돌려가며 디버깅할 수 있습니다.
이러한 Redux의 주요 개념들을 활용하면 애플리케이션의 상태를 체계적으로 관리하고, 예측 가능한 방식으로 상태 변경을 처리할 수 있습니다.