๋ฆฌ์กํธ์์ ์ํ ๊ด๋ฆฌ๋ ๊ธฐ๋ณธ์ ์ผ๋ก props๋ฅผ ํตํด ์ด๋ฃจ์ด์ง๋ค. ํ์ง๋ง ์ ํ๋ฆฌ์ผ์ด์
์ด ์ปค์ง๊ณ ์ปดํฌ๋ํธ๊ฐ ๋ง์์ง์๋ก ์ํ๋ฅผ ์ฌ๋ฌ ์ปดํฌ๋ํธ์์ ๊ณต์ ํ๊ฑฐ๋ ๊น๊ฒ ์ ๋ฌํด์ผ ํ๋ ์ํฉ์ด ๋ฐ์ํ๋ฉด์ ์ฝ๋๊ฐ ๋ณต์กํด์ง ์ ์๋ค.
์ด๋ฌํ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ณ ์ํ ๊ด๋ฆฌ๋ฅผ ๋ณด๋ค ์ฒด๊ณ์ ์ด๊ณ ์์ธก ๊ฐ๋ฅํ๊ฒ ํ๊ธฐ ์ํด ๋ฑ์ฅํ ๊ฒ์ด Redux์ด๋ค. ์ ํ๋ฆฌ์ผ์ด์
์ ๋ชจ๋ ์ํ๋ฅผ ํ๋์ ์ค์ ์ ์ฅ์(store)์ ๋ณด๊ดํ๊ณ ์ํ๋ฅผ ๋ณ๊ฒฝํ ๋์๋ ๋ฐ๋์ ์ก์
(action)๊ณผ ๋ฆฌ๋์(reducer)๋ฅผ ํตํด ๋ณ๊ฒฝํ๋ค.
์ด๋ฌํ ๊ตฌ์กฐ ๋๋ถ์ ์ํ ๋ณํ์ ํ๋ฆ์ด ๋ช
ํํ๊ณ ๋๋ฒ๊น
์ด ์ฌ์์ง๋ฉฐ ๊ท๋ชจ๊ฐ ํฐ ํ๋ก์ ํธ์์๋ ์ผ๊ด๋ ๋ฐฉ์์ผ๋ก ์ํ๋ฅผ ๊ด๋ฆฌํ ์ ์๋ค.
Redux๋ 3๊ฐ์ง ํต์ฌ ๊ตฌ์ฑ์์๋ก ๋์ํ๋ค.
Reducer
๊ทธ๋ฆฌ๊ณ ์ด ๊ตฌ์ฑ์์๋ค์ ์ฐ๊ฒฐํด ์ฃผ๋ ์ญํ ์ ํ๋ ๊ฒ์ด ๋ฐ๋ก Dispatch์ด๋ค.
Store๋ ์ฑ์ ์ ์ฒด ์ํ(state)๋ฅผ ๋ณด๊ดํ๋ ๊ฐ์ฒด๋ก์จ ํ๋์ ์ฑ์ ํ๋์ store๊ฐ ์กด์ฌํ๊ณ ์ด store๋ ๋ชจ๋ ์ปดํฌ๋ํธ๊ฐ ๊ณต์ ํ๋ค.
createStore()๋ก ์์ฑํ๋ค.
import { createStore, combineReducers } from "redux";
import { counterReducer } from './counterReducer';
const rootReducer = combineReducers({
counter: counterReducer
});
export const store = createStore(rootReducer);
์ดํ Provider๋ก App ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ธ์ค๋ค.
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
<Counter />
</Provider>
);
Provider๋ ๋ฆฌ์กํธ ์ปดํฌ๋ํธ ํธ๋ฆฌ ์ ์ฒด์ Redux์ store๋ฅผ ์ ๋ฌํ๋ ์ญํ ์ ํ๋ฉฐ ๋ด๋ถ์ ๋ชจ๋ ์ปดํฌ๋ํธ๋ค์ด Redux ์ํ์ ์ ๊ทผํ ์ ์๊ฒ ๋ง๋ค์ด์ค๋ค.
Action์ ์ํ ๋ณ๊ฒฝ์ด ํ์ํ๋ค๋ ์์ฒญ์ ์ ๋ฌํ๋ ๊ฐ์ฒด์ด๋ค. ํญ์ type์ด๋ผ๋ ํ์ ์์ฑ์ ๊ฐ์ง๋ฉฐ ์ํฉ์ ๋ฐ๋ผ payload ๊ฐ์ ์ถ๊ฐ ๋ฐ์ดํฐ๋ ํฌํจํ ์ ์๋ค.
const incrementAction = {
type: 'INCREMENT',
payload: 1
};
Reducer๋ ํ์ฌ ์ํ์ ์ก์ ์ ๋ฐ์์ ์๋ก์ด ์ํ ๊ฐ์ฒด๋ฅผ ๋ฐํํ๋ ํจ์์ด๋ค. ์ํ๋ฅผ ์ง์ ์์ ํ์ง ์๊ณ ํญ์ ์๋ก์ด ์ํ ๋ฐํํจ์ผ๋ก์จ ์ํ ๋ณ๊ฒฝ์ ๊ด๋ฆฌํ๋ค.
const counterReducer = (state = { value: 0 }, action) => {
switch (action.type) {
case 'INCREMENT':
return { value: state.value + action.payload };
default:
return state;
}
};
Dispatch๋ ์ก์ ์ ๋ฆฌ๋์์ ์ ๋ฌํด์ ์ํ๋ฅผ ๋ณ๊ฒฝํ๋๋ก ํ๋ ํจ์์ด๋ค. ์ปดํฌ๋ํธ ๋ด๋ถ์์ dispatch()๋ฅผ ํธ์ถํ๋ฉด ํด๋น ์ก์ ์ด ์คํ๋์ด ๋ฆฌ๋์๋ก ์ ๋ฌ๋๊ณ ๊ทธ์ ๋ฐ๋ผ ์ํ๊ฐ ์ ๋ฐ์ดํธ๋๋ค.
import { useDispatch, useSelector } from "react-redux";
const Counter = () => {
const dispatch = useDispatch();
const count = useSelector((state) => state.counter.value);
const incrementAction = {
type: 'INCREMENT',
payload: 1
};
const handleClick = () => {
dispatch(incrementAction);
};
return (
<div>
<p>์นด์ดํธ: {count}</p>
<button onClick={handleClick}>+1 ์ฆ๊ฐ</button>
</div>
);
};
export default Counter;
