React, Redux

2024. 12. 26. 17:24웹 개발

npm install redux react-redux
npm install react

 

App.jsx

import { createStore } from 'redux';
import { Provider, useDispatch, useSelector } from 'react-redux';

// Define actions (액션 정의)
const ACTION_ENCREMENT = 'INCREMENT';
const ACTION_DECREMENT = 'DECREMENT';

// Action creators (액션 생성자 함수)
const incrementAction = () => ({ type: ACTION_ENCREMENT });
const decrementAction = () => ({ type: ACTION_DECREMENT });

// Define reducer (리듀서 정의)
const initialState = { count: 0 };

const counterReducer = (state = initialState, action) => {
    switch (action.type) {
        case ACTION_ENCREMENT:
            return { count: state.count + 1 };
        case ACTION_DECREMENT:
            return { count: state.count - 1 };
        default:
            return state;
    }
}

// Create store (스토어 생성)
const store = createStore(counterReducer);

// Define component (컴포넌트 정의)
const Counter = () => {
    const dispatch = useDispatch();
    const count = useSelector((state) => state.count);
    return (
        <div style={{
                textAlign: 'center',
                marginTop: '50px'
            }}>
            <h1>Counter: {count}</h1>
            <button onClick={() => dispatch(incrementAction())}>Increment</button>
            <button onClick={() => dispatch(decrementAction())}>Decrement</button>
        </div>
    );
}

// App component (앱 컴포넌트)
function App() {
    return (
        <Provider store={store}>
            <Counter />
        </Provider>
    );
}

export default App;

 

https://stackblitz.com/edit/vitejs-vite-kmhyjuxf?embed=1&file=src%2FApp.jsx

 

'웹 개발' 카테고리의 다른 글

React, Redux, To-Do List  (0) 2024.12.30
React + Redux, useStore, useDispatch  (1) 2024.12.27
React, Context, useContext Hook  (1) 2024.12.26
React, Context + Consumer  (0) 2024.12.26
React, usePromise 커스텀 훅  (0) 2024.12.23