React Hook - Reducer, useReducer

BANG·2025년 8월 27일

useReducer

action

dispatch

reducer

별코딩 예시 참고


import { useReducer, useState } from 'react';

const reducer = (currentMoney, action) => {
  switch (action.type){
    case 'up':
      return currentMoney + action.payload;
    case 'down':
      return currentMoney - action.payload;
    default:
      return currentMoney;
  } 
};

const App = () => {
  const [number, setNumber] = useState(0);
  const [money, dispatch] = useReducer(reducer, 0);
  
  return (
    <div>
      <h2>은행</h2>
      <p>잔고: {money}</p>
      <input type='number' value={number} step="1000"
      onChange={(event) => setNumber(parseInt(event.target.value))} />
      <button onClick={() => 
        {dispatch({type: 'up', payload: number})}}>
          예금</button>
      <button onClick={() => 
        {dispatch({type: 'down', payload: number})}}>
          출금</button>
    </div>
  )
};

export default App;
import { useReducer, useState } from 'react';
import Student from './Component/Student';

const reducer = (curruntStudents, action) => {
  switch(action.type){
    case 'add':
      const name = action.payload.name;
      const newStudent = {
        id: curruntStudents.count + 1,
        name,
        isHere: false
      };
      return {
        count: curruntStudents.count + 1,
        students: [...curruntStudents.students, newStudent],
      };
    case 'delete':
      return {
        count: curruntStudents.count - 1,
        students: curruntStudents.students.filter(student => student.id !== action.payload.id)
      };
    case 'mark':
      return {
        count: curruntStudents.count,
        students: curruntStudents.students.map(student => {
          if (student.id === action.payload.id){
            return {...student, isHere: !student.isHere}
          }
          return student;
        })
      };
    default:
      return curruntStudents;
  }
};

const initStudent = {
  count: 0,
  students: []
};

const App = () => {
  const [name, setName] = useState('');
  const [studentInfo, dispatch] = useReducer(reducer, initStudent);

  return (
    <div>
      <h1>출석부</h1>
      <p>총 학생수: ?</p>
      <input 
        type='text'
        placeholder='이름'
        value={name}
        onChange={(event) => setName(event.target.value)} />
      <button
        onClick={() => {dispatch({ type: 'add', payload: {name} });}}
      >추가</button>
      {studentInfo.students.map((student) => {
        return (
        <Student key={student.id} name={student.name} 
        dispatch={dispatch} id={student.id} isHere={student.isHere} />
      );
      })}
    </div>
  )
};

export default App;

생활코딩 예시 참고
리듀서


profile
Record Everything!!

0개의 댓글