본문 바로가기
개념/React

React) useReducer - counter

by kiseno 2025. 3. 17.
728x90
반응형
SMALL
import {useReducer} from 'react';

function reducer(state, action){
    switch (action.type) {
        case 'INCREMENT': return {value : state.value + 1};
        case 'DECREMENT': return {value : state.value - 1};
        default: return state;
    }
}

const Counter = () => {
    const [state, dispatch] = useReducer(reducer, {value : 0});

    return (
        <div>
            <p> current counter value : <b>{state.value}</b></p>
            <button onClick = {() => dispatch({type : 'INCREMENT'})}>+1</button>
            <button onClick = {() => dispatch({type : 'DECREMENT'})}>-1</button>
        </div>
    );
};

//App.js
// import Counter from './frames/Hook/useReducer/Counter';
//
// const App = () => {
//     return <Counter/>;
// };
//
// export default App;
export default Counter;

### Component Breakdown

1. **Reducer Function**:
   ```javascript
   function reducer(state, action) {
       switch (action.type) {
           case 'INCREMENT':
               return {value: state.value + 1};
           case 'DECREMENT':
               return {value: state.value - 1};
           default:
               return state;
       }
   }
   ```
   - The `reducer` function defines how the state transitions occur based on different actions. It handles two actions: `INCREMENT` and `DECREMENT`.
   - **`INCREMENT`**: Increases the `value` property of the state object by 1.
   - **`DECREMENT`**: Decreases the `value` property of the state object by 1.
   - **`default`**: Returns the current state unchanged if the action type is not recognized.

2. **Using useReducer**:
   ```javascript
   const [state, dispatch] = useReducer(reducer, {value: 0});
   ```
   - `useReducer` is initialized with the `reducer` function and an initial state of `{value: 0}`. This sets up `state` to be an object with a `value` property starting at 0.
   - `dispatch` is a function provided by `useReducer` that you can call to update the state based on the specified action.

3. **Component UI**:
   ```javascript
   return (
       <div>
           <p>current counter value: <b>{state.value}</b></p>
           <button onClick={() => dispatch({type: 'INCREMENT'})}>+1</button>
           <button onClick={() => dispatch({type: 'DECREMENT'})}>-1</button>
       </div>
   );
   ```
   - The component renders a paragraph displaying the current value of the counter and two buttons to change the counter value.
   - The buttons are equipped with `onClick` handlers that call `dispatch` with an action object. When clicked, they send either an `INCREMENT` or `DECREMENT` action to the reducer, which updates the state accordingly.

### Practical Use

This pattern is a clean and efficient way to handle state that involves multiple sub-values or complex state logic. Using `useReducer` helps keep the state transitions explicit and predictable, which can be a significant advantage in more complex components or applications. It also allows for easier testing and debugging since the state management logic is decoupled from the component itself and can be easily isolated.

### Conclusion

Your `Counter` component is a good example of how `useReducer` can be utilized effectively for managing state transitions in functional React components. It's particularly useful in cases where you expect the component's state logic to grow more complex over time, providing scalability and maintainability benefits. This approach also aligns well with Redux-style management patterns, making it easier for developers familiar with Redux to adapt and manage local component state in React.

728x90
반응형
LIST

'개념 > React' 카테고리의 다른 글

React) local parameter - example 1  (0) 2025.03.19
React) local parameter - example 2  (0) 2025.03.18
React) useReducer - info  (0) 2025.03.16
React) React 초기 세팅  (0) 2025.03.15
React Component) change to root component to class component  (0) 2025.01.11