React - useReducer 사용해보기

thisishwarang·2023년 1월 29일
0

원래 useState를 사용하여 객체의 값을 변경, 추가, 삭제 등 상태관리를 하다가 useReducer를 활용한 상태관리법을 배웠다.
이 useReducer를 사용하면 컴포넌트의 상태 업데이트 로직을 컴포넌트에서 분리시킬 수 있다.

초기 person이란 state에 내 이름, 나이, 친구들 이란 key값에 배열로 친구들의 이름, 나이 가 중첩 객체로 저장되어 있다. 이때 내용을 변경, 추가, 삭제를 useReducer를 사용하여 해보자.

(AppFriends.jsx)
const [person, dispatch] = useReducer(personReducer, initialPerson)

person은 state, personReducer는 reducer함수 이름, initialPerson은 초기 person의 state값이 저장되어있는 변수이다.

(person-reducer.js)
export default function personReducer(person, action) {
    switch(action.type) {
        case 'updated' : {
            const {prev, current} = action;
            return {
                ...person,
                mentors : person.mentors.map((mentor) => 
                    mentor.name === prev
                    ? {...mentor, name : current}
                    : mentor
            )
            }
        }
        case 'added' : {
            const {name, title} = action;
            return {
                ...person,
                mentors : [...person.mentors, {name, title}],
            }
        }
        case 'deleted' : {
            return {
                ...person,
                mentors : person.mentors.filter((mentor) => 
                    mentor.name !== action.name || mentor.title !== action.title
                )
            }
        }
        default : {
            throw Error(`알수 없는 액션 타입이다: ${action.type}}`)
        }
    }
}

personReducer함수에 매개변수로 person state와 action정보를 받아온다.
이후 action의 type에 따라 상태정보를 업데이트 해주면 된다.

이후 이 함수를 사용할때는

(AppFriend.jsx)
//사용하려는 함수 안에서
dispatch({type : 'updated', prev, current})

이와 같이 상태 type, 전달하려는 변수를 적어서 호출하면 된다

0개의 댓글