Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

new_bird-hyun

React의 상태 관리 심화 - useContext와 useReducer의 조합 본문

코딩 공부

React의 상태 관리 심화 - useContext와 useReducer의 조합

새혀니 2024. 12. 14. 18:58
import React, { createContext, useReducer, useContext } from 'react'; const CounterContext = createContext(); const initialState = { count: 0 }; function counterReducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(`Unknown action: ${action.type}`); } } function CounterProvider({ children }) { const [state, dispatch] = useReducer(counterReducer, initialState); return ( {children} ); } function Counter() { const { state, dispatch } = useContext(CounterContext); return (

Count: {state.count}

); } function App() { return ( ); } export default App; useContext와 useReducer를 함께 사용하면 Redux의 기본 기능을 대체할 수 있음