useReducer 복잡한 상태관리 로직분리
본문 바로가기

Frontend/React

useReducer 복잡한 상태관리 로직분리

useState로 데이터를 관리하다보면 crud할때 계속 setState를 사용하다보니 코드줄이 길어짐 => 밖으로 빼서 깔끔하게하기위함

로직은 useState와 매우 비슷함

1. 기존 useState를 지우고 그자리에 useReducer를 넣는다.

const [data, dispatch] = React.useReducer(reducer, [])

2. 외부에(app컴포넌트 밖 혹은 다른파일) reducer 함수에 action type에 따른 로직 준비

        const reducer = (state, action) => {
            switch(action.type){
                case 'INIT':{
                    return action.data
                }
                case 'CREATE':{
                    const newItem = {
                        ...action.data
                    }
                    return [newItem, ...state]
                }
                case 'REMOVE':{
                    return state.filter((it)=> it.id !== action.targetId)
                }
                case 'EDIT':{
                    state.map(it => it.id === action.targetId ? {...it, content:action.newContent, title:action.newTitle} : it)
                }
                default: state
            }
        }

3. 기존 setState자리를 dispatch대체

 

데이터 호출

dispatch({type:'INIT', data:initData})

reducer함수에서는 action.data로 호출하여 initData를 사용

 

Create

데이터호출 방법과 동일

 

Remove

dispatch({type:'REMOVE',targetId})

reducer함수에서는 action.tokenId로 targetId를 받아옴

 

Update

remove와 동일

 

반응형