Skip to content

[3주차] useReducer 직접 구현하기 #11

@roksui

Description

@roksui

MyReact.js

import { useState } from 'react';

export function useReducer(reducer, initialState) {
  const [state, setState] = useState(initialState);

  function dispatch(action) {
    const nextState = reducer(state, action);
    setState(nextState);
  }

  return [state, dispatch];
}

Array.prototype.reduce() 메소드와의 비교

reduce() 메소드는 두 개의 파라미터를 받는다: reducer 함수와 초기 값

const numbers = [1, 2, 3, 4, 5];
const reducer = (accum, curr) => accum + curr; // reducer 함수
const initialValue = 5; // 초기 값

const sumOfNumbers = numbers.reduce(reducer, initialValue);

console.log(sumOfNumbers); // prints 20
// ---------------------------------------
function reduce(reducer, initialValue) {
    let accum = initialValue;
    for (let i = 0; i < this.length; i++) {
        accum = reducer(accum, this[i]);
    }
    return accum;
}

// ---------------------------------------
function tasksReducer(tasks, action) {
    switch (action.type) {
        case 'added': {
            return [
                ...tasks,
                {
                    id: action.id,
                    text: action.text,
                    done: false,
                 }
             ];
        }
        case 'changed': {
            return tasks.map((t) => {
                if (t.id === action.task.id) return action.task;
                else return t;
            });
        }
        case 'deleted': {
            return tasks.filter((t) => t.id !== action.id);
        }
        // default case..
    }
}  
let initialState = [];
let actions = [
  { type: 'added', id: 1, text: 'Visit Kafka Museum' },
  { type: 'added', id: 2, text: 'Watch a puppet show' },
  { type: 'deleted', id: 1 },
  { type: 'added', id: 3, text: 'Lennon Wall pic' },
];

let finalState = actions.reduce(tasksReducer, initialState);

// finalState
[
  {
    "id": 2,
    "text": "Watch a puppet show",
    "done": false
  },
  {
    "id": 3,
    "text": "Lennon Wall pic",
    "done": false
  }
]

React의 useReducer 훅은 reduce와 비슷하게 동작한다.
위 예시처럼 마지막 상태를 한 번에 계산 하기 위해서는 Array.prototype.reduce를 사용할 수도 있겠다.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions