Redux는 상태 관리를 효율적으로 하기 위한 라이브러리다.
애플리케이션의 상태를 중앙 저장소(store) 에 보관하고, 필요한 컴포넌트가 그 상태를 쉽게 가져다 쓸 수 있도록 도와준다.
구성 요소
- Store: 애플리케이션의 전역 상태를 관리하는 저장소.
- Action: 상태를 변경하는 유일한 방법. 객체 형태로 { type: "액션_이름" } 을 가진다.
- Reducer: 현재 상태와 액션을 받아 새로운 상태를 반환하는 순수 함수.
- useSelector: Redux의 store에서 상태를 가져오는 React Hook.
import { useSelector } from 'react-redux';
const MyComponent = () => {
const count = useSelector((state) => state.counter.value);
return <div>Count: {count}</div>;
};
!! useSelector를 사용하면 store에서 원하는 데이터를 가져올 수 있다. !!
dispatch는 Redux에서 상태를 변경하는 유일한 방법이다.
액션 객체를 dispatch를 통해 리듀서로 보내면, 상태가 변경된다.
const incrementAction = { type: "counter/increment" };
dispatch(incrementAction);
import { useDispatch } from 'react-redux';
const MyComponent = () => {
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: "counter/increment" })}>
증가
</button>
);
};
!! dispatch를 통해 상태를 업데이트할 수 있다. !!
- payload
액션 객체가 데이터를 포함할 때, 일반적으로 payload라는 속성을 사용한다.const setNameAction = { type: "user/setName", payload: "John Doe" }; dispatch(setNameAction);리듀서에서는 payload 값을 이용해 상태를 변경할 수 있다.
function userReducer(state, action) { switch (action.type) { case "user/setName": return { ...state, name: action.payload }; default: return state; } }- Ducks 패턴
Redux 관련 코드(action, reducer)를 하나의 파일에 모아 관리하는 방식이다.
일반적인 Redux 구조에서는 actions.js, reducers.js가 따로 있지만, Ducks 패턴을 사용하면 하나의 파일에서 관리할 수 있다.const INCREMENT = "counter/increment"; const DECREMENT = "counter/decrement"; export const increment = () => ({ type: INCREMENT }); export const decrement = () => ({ type: DECREMENT }); const initialState = { value: 0 }; export default function counterReducer(state = initialState, action) { switch (action.type) { case INCREMENT: return { ...state, value: state.value + 1 }; case DECREMENT: return { ...state, value: state.value - 1 }; default: return state; } }Ducks 패턴을 사용하면 코드가 더 직관적이고 유지보수가 쉬워진다.