React

[React #31] ToDo List - useState에서 useReducer로 변경

PEAZH 2024. 3. 18. 14:29
반응형

🌵 Step 01

useReducer의 훅을 호출한 뒤, reducer 함수를 생성하고 인수로 전달하고 초기값도 전달해 줌

function reducer() {}

function App() {
    const [todos, dispatch] = useReducer(reducer, mokData);
}

🌵 Step 02

상태 변화 함수에서 dispatch를 호출한 뒤 Action 객체를 생성하여 전달

const onCreate = (content) => {
  dispatch({
    type: 'CREATE',
    data: {
      id: idRef.current,
      isDone: false,
      content: content,
      data: new Date().getTime(),
    },
  });
};

🌵 Step 03

reducer 함수에 코드 작성하기

function reducer(state, action) {
  switch (action.type) {
    case 'CREATE':
      return [action.data, ...state];
  }
}

🌵 최종코드

import { useState, useRef, createContext, useReducer } from 'react';
import './App.css';
import Header from './components/Header';
import Editor from './components/Editor';
import List from './components/List';

function reducer(state, action) {
  switch (action.type) {
    case 'CREATE':
      return [action.data, ...state];
    case 'UPDATE':
      return state.map((todo) =>
        todo.id === action.targetId ? { ...todo, isDone: !todo.isDone } : todo
      );
    case 'DELETE':
      return state.filter((todo) => todo.id !== action.targetId);
    default:
      state;
  }
}

function App() {
  const [todos, dispatch] = useReducer(reducer, mokData);
  const idRef = useRef('4');

  const onCreate = (content) => {
    dispatch({
      type: 'CREATE',
      data: {
        id: idRef.current,
        isDone: false,
        content: content,
        data: new Date().getTime(),
      },
    });
  };

  const onUpdate = (targetId) => {
    dispatch({
      type: 'UPDATE',
      targetId: targetId,
    });
  };

  const onDelete = (targetId) => {
    dispatch({
      type: 'DELETE',
      targetId: targetId,
    });
  };

  return (
    <div className='App'>
      <Header />
        <Editor />
        <List todos={todos} onUpdate={onUpdate} onDelete={onDelete} />
    </div>
  );
}

export default App;

📌 리액트에서 state를 관리할 때 배열 안에 객체가 들어가는

복잡한 구조는 useReducer를 이용해서 관리하는 것이 일반적

 

 

 

참고자료

이정환 Winterlood, '한입 크기로 잘라 먹는 리액트(React.js) : 기초부터 실전까지'
반응형