Boilerplate ์ฝ๋๋ ๋ฐ๋ณต์ ์ผ๋ก ์์ฑํด์ผ ํ๋ ์ฝ๋๋ฅผ ์๋ฏธํ๋ค.
ํนํ, Redux๋ ์ํ ๊ด๋ฆฌ๋ฅผ ์ํด ๋ง์ Boilerplate ์ฝ๋๊ฐ ํ์ํ๊ธฐ ๋๋ฌธ์ ์ค์ ์ด ๋ณต์กํ๊ณ ์ฝ๋๊ฐ ๊ธธ์ด์ง๋ ๋ฌธ์ ๊ฐ ์กด์ฌํ๋ค.
Redux๋ฅผ ์ฌ์ฉํ๋ ค๋ฉด ์ต์ํ Action, Reducer, Store๋ฅผ ์ค์ ํด์ผ ํ๊ณ , ์ํ๋ฅผ ๋ณ๊ฒฝํ๋ ค๋ฉด ๋ฐ๋์ dispatch(action)์ ํธ์ถํด์ผ ํ๋ค.
์ด ๊ณผ์ ์ ๊ฑฐ์น๋ค ๋ณด๋ฉด ๋ฐ๋ณต์ ์ด๊ณ ๋ถํ์ํ ์ฝ๋๊ฐ ๋ง์์ง๋ค.
// actions.js
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const increment = () => ({ type: INCREMENT });
const decrement = () => ({ type: DECREMENT });
โ ์ํ๋ฅผ ๋ณ๊ฒฝํ๋ ค๋ฉด ๋ฐ๋์ ์ก์ ํ์ ๊ณผ ์ก์ ์์ฑ ํจ์(action creator)๋ฅผ ์ ์ํด์ผ ํจ.
// reducer.js
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
โ reducer๋ ์ํ๋ฅผ ๋ณ๊ฒฝํ๋ ์ญํ ์ ํ์ง๋ง, switch-case ๋ฌธ์ด ๊ธธ์ด์ง๊ณ ๋ณต์กํด์ง๋ ๋ฌธ์ ๊ฐ ์กด์ฌ.
// store.js
import { createStore } from 'redux';
import counterReducer from './reducer';
const store = createStore(counterReducer);
export default store;
โ ์ํ๋ฅผ ์ ์ฅํ๋ store๋ ๋ฐ๋ก ๋ง๋ค์ด์ผ ํจ.
// Counter.js
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';
function Counter() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<h1>{count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
);
}
โ
์ํ๋ฅผ ๊ฐ์ ธ์ค๋ ค๋ฉด useSelector(), ๋ณ๊ฒฝํ๋ ค๋ฉด dispatch(action)์ ์จ์ผ ํด์ ์ฝ๋๊ฐ ๊ธธ์ด์ง.
Redux์ ๋ณต์กํ ์ค์ ์์ด, ๋จ ๋ช ์ค์ ์ฝ๋๋ง์ผ๋ก ๋์ผํ ๊ธฐ๋ฅ์ ๊ตฌํ ๊ฐ๋ฅ!
import { create } from 'zustand';
// Zustand ์คํ ์ด ์์ฑ (๋จ 1์ค)
const useCounterStore = create((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
}));
// ์ปดํฌ๋ํธ์์ ์ฌ์ฉ
function Counter() {
const { count, increase, decrease } = useCounterStore();
return (
<div>
<h1>{count}</h1>
<button onClick={increase}>+</button>
<button onClick={decrease}>-</button>
</div>
);
}
โ Redux์ ๋นํด ์ฝ๋๊ฐ ์์ฒญ ์งง์์ง๊ณ , ๊ตฌ์กฐ๊ฐ ์ง๊ด์ !
๐ฏ Boilerplate ์ฝ๋์ ํต์ฌ ๋ฌธ์ ์
โ ๊ฒฐ๋ก : Redux๋ ๊ฐ๋ ฅํ์ง๋ง, ์ค์ ์ด ๋ฒ๊ฑฐ๋กญ๊ณ Boilerplate ์ฝ๋๊ฐ ๋ง์ ๊ด๋ฆฌ๊ฐ ์ด๋ ต๋ค. ๋ฐ๋ฉด, Zustand๋ ๋ ๊ฐ๊ฒฐํ๊ณ ์ฌ์ฉํ๊ธฐ ์ฝ๋ค! ๐