개념/React

React) useReducer - info

kiseno 2025. 3. 16. 21:20
728x90
반응형
SMALL
import {useReducer} from 'react';

function reducer(state,action){
    return {
        ...state,
        [action.name]: action.value
    };
}

const Info = () => {
    const [state, dispatch] = useReducer(reducer, {
        name: '',
        nickname: ''
    });
    const {name, nickname} = state;
    const onChange = e => {
        dispatch(e.target);
    };

    return (
        <div>
            <div>
                <input name = "name" value = {name} onChange = {onChange}/>
                <input name = "nickname" value = {nickname} onChange = {onChange}/>
            </div>
            <div>
                <div>
                    <b>name : </b> {name}
                </div>
                <div>
                    <b>nickname : </b> {nickname}
                </div>
            </div>
        </div>
    );
};
//App.js
// import Info from './frames/Hook/useReducer/info';
//
// const App = () => {
//     return <Info/>;
// };
//
// export default App;
export default Info;

### Reducer Function

```javascript
function reducer(state, action) {
    return {
        ...state,
        [action.name]: action.value
    };
}
```

- **Functionality**: This reducer function updates the state by taking the current state and an action object. The action object is expected to have `name` and `value` properties, which correspond to the name of the input and the new value to be stored, respectively.
- **State Spread**: By spreading the current state (`...state`), the reducer ensures that only the property specified by `action.name` is updated, while all other state properties remain unchanged.

### Component Setup

```javascript
const Info = () => {
    const [state, dispatch] = useReducer(reducer, {
        name: '',
        nickname: ''
    });
    const {name, nickname} = state;
    const onChange = e => {
        dispatch(e.target);
    };

    return (
        <div>
            <input name="name" value={name} onChange={onChange}/>
            <input name="nickname" value={nickname} onChange={onChange}/>
            <div>
                <b>name: </b> {name}
                <b>nickname: </b> {nickname}
            </div>
        </div>
    );
};
```

- **State Initialization**: The `useReducer` hook initializes the state with two properties: `name` and `nickname`, both set to empty strings. This initial state forms the basis for the input fields in the form.
- **Dispatching Actions**: The `onChange` handler dispatches actions directly based on the event target (`e.target`), which contains the `name` and `value` properties of the input element that triggered the change. This approach leverages HTML input names and values directly, aligning with the reducer's expectations.
- **Inputs and Display**: The component renders two input fields for `name` and `nickname`, both controlled by the state via the `useReducer` hook. It also displays the current state of these inputs dynamically below them, demonstrating a typical pattern for displaying reactive form data.

### Enhanced Functionalities

This setup is particularly well-suited for forms with multiple fields and can be extended or adapted for various types of inputs. To enhance usability and maintainability:
- **Validation**: You could add validation logic either inside the `onChange` handler before dispatching actions or within the reducer function itself.
- **Form Submission**: Integrating a submit button that handles the final form data (e.g., posting to a server) would make the component more practical for real-world applications.
- **Complex State Structures**: For more complex forms, the reducer can be expanded to handle nested state objects or arrays, accommodating more sophisticated form structures.

### Conclusion

Your implementation of the `Info` component using `useReducer` is clean and scalable, making it ideal for managing complex form states in React. This approach minimizes re-renders and optimizes performance by only updating relevant parts of the state, making it a robust solution for larger or more dynamic forms. It also keeps the component's logic centralized and easier to manage, enhancing code readability and maintenance.

728x90
반응형
LIST