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와 동일
반응형
'Frontend > React' 카테고리의 다른 글
[env-cmd] 리액트 env 사용방법 (0) | 2023.06.26 |
---|---|
[build] 에러 Cannot convert a BigInt value to a number 해결 (0) | 2023.06.20 |
Context API 사용법 (0) | 2023.04.06 |
React jsx안에서 `${}`쓰고싶을때 (0) | 2023.03.27 |
Context API _context undefined 에러 (0) | 2023.01.08 |