며칠간 redux를 공부하며 이 작동 원리를 드디어 어렴풋이 깨달았다. 아직도 완벽한 건 아니지만 GPT와 대화하며 아웃라인은 잡았다고 생각한다. 아래는 내가 이해한 작동 원리이다.
import React from 'react';
import { Provider } from 'react-redux';
import Clock from './components/Clock';
import { useStore } from './store';
const App = () => {
const store = useStore();
return (
<Provider store={store}>
<Clock />
</Provider>
);
};
export default App;
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { AppState } from '../store';
const Clock = () => {
const today = useSelector<AppState, Date>((state) => state.today);
const dispatch = useDispatch();
useEffect(() => {
const id = setInterval(() => dispatch({ type: 'setToday', today: new Date() }), 1000);
return () => clearInterval(id);
}, [dispatch]);
return (
<div className="flex flex-col items-center justify-center p-2">
<p className="text-3xl text-blue-600">{today.toLocaleTimeString()}</p>
<p className="text-2xl text-blue-400">{today.toLocaleDateString()}</p>
</div>
);
};
export default Clock;
import type {Actions} from './actions'
import type {AppState} from './AppState'
const initialAppState = {
today: new Date();
}
export const rootReducer = (state: AppState = initialAppState, action: Actions) => {
switch (action.type) {
case 'setToday':
return { ...state, today: action.today };
default:
return state;
}
}
import { configureStore } from '@reduxjs/toolkit';
import { useMemo } from 'react';
import { rootReducer } from './rootReducer';
const initializeStore = () => {
const store = configureStore({ reducer: rootReducer, middleware: [] });
return store;
};
export function useStore() {
const store = useMemo(() => initializeStore(), []);
return store;
}