useAuthContext ์์ dispatch ๋ฅผ ์ฌ์ฉํ ๋ ์๋ฌ๊ฐ ๋์.
Context์ dispatch์ ํ์
์ ์ ๋ฃ์ด์ฃผ์๋ฉด ๋ฉ๋๋ค :)์ฐพ์ผ์ ๊ฒ์ฒ๋ผ Context์ ํ์
์ null๋ก ์ฃผ์
์ ์๋ฌด๊ฒ๋ ์๋๋ฐ dispatch๋ฅผ ๊บผ๋ด์ฐ๋ ค๊ณ ํด์ ์๊ธด ์ค๋ฅ์
๋๋ค. ์ฐธ๊ณ ํ ๋งํ ์์ ์ฝ๋๋ฅผ ๋๋ฆฌ๊ฒ ์ต๋๋ค. ์ฐ์ตํด๋ณด์๊ณ ์ ์ฉํ์๋ฉด ์ข์๋ฏ ํด์. ํ์ดํ
์
๋๋ค! import { Dispatch, createContext, useContext, useReducer } from 'react'; type Action = { type: 'increment' } | { type: 'decrement' }; function counterReducer(state: number, action: Action): number { switch (action.type) { case 'increment': return state + 1; case 'decrement': return state - 1; default: throw new Error('Unhandled action type'); } } const initialState = 0; type CounterContextType = { state: number; dispatch: Dispatch; }; const CounterContext = createContext({ state: initialState, dispatch: () => {}, }); function CounterProvider(props: { children }) { const [state, dispatch] = useReducer(counterReducer, initialState); const value = { state, dispatch }; return ; } function useCounterContext(){ const context = useContext(CounterContext); return context } function Counter() { const {state, dispatch} = useCounterContext(); const handleIncrement = () => dispatch({ type: 'increment' }); const handleDecrement = () => dispatch({ type: 'decrement' }); return ( {state} + - ); } function App() { return ( ); } export default App;