React 에서 useState hook 및 Recoil Atom을 사용하여 React state를 관리 할 수 있습니다.
React Recoil Atom으로 팝업 관리하기
Recoil Atom 공식 문서를 보면 상세하게 알 수 있습니다. 단순하게, Recoil은 상태를 관리하는 라이브러...
blog.naver.com
따라서 관리할 때 state 변경(set)이 발생하게 되는데,
그때 사용하는 불변성관리 라이브러리가 immer입니다.
recoil을 사용할때 아래와 같은 방법으로 해당 state를 변경할 수 있습니다.
const alertAtom = atom({ key: 'common/alert', default: { title: '', content: '', }, }); const setAlert = useSetRecoilState(alertAtom); // or const [alertState, setAlert] = useRecoilState(alertAtom); useEffect(()=>{ setAlert({ title: '제목' }); // alertState : {title: '제목'} setAlert({ content: '내용' }); // alertState : {content: '내용'} setAlert(...alertState, { content: '내용' }); alertState : {title:'제목', content: '내용'} setAlert({ title: '제목' }) // Rendering 중복실행 }, [])
위와 같이 변경했을때
1. 해당값 전체에 새로운 값을 변경(set)하기 때문에 기존값은 유지되지 않습니다.
- setAlert({ title: '제목' }), setAlert({ content: '내용' }) : 내용 유지안함
2. 또한 같은 값을 변경(set)해도 불변이 유지되지 않고 object를 참조하는 주소가 변경되기 때문에
다른 값으로 인지하고 Rendering이 재 실행됩니다.
- setAlert({ title: '제목' });, setAlert({ title: '제목' }) : 같은 값이지만 Rendering 중복 실행
이때 immer를 사용하여 해당 state를 관리합니다.
produce(baseState, recipe: (draftState) => void): nextState
setAlert( produce((draft) => { draft.title = '제목'; }) ); setAlert( produce((draft) => { draft.content = '내용'; }) );
위와 같이 하면 참조 주소는 유지하여 불변성이 유지하고 해당 값이 변경되기 때문에,
1. 다른 값들은 유지되고
2. 동일한 값으로 변경되어도 Rendering 되지 않습니다.
해당 내용을 function으로 변경하면 아래와 같이 사용가능합니다.
const updateAtom = (newValue: { title?: string; content?: string }) => { setAlert( produce((draft) => { for (const [key, value] of Object.entries(newValue)) { Object.assign(draft, { [key]: value }); } }) ); }; ... updateAtom({title:'제목'}) updateAtom({content:'내용'})
React Query - useQuery 맛보기 (0) | 2023.03.01 |
---|---|
React 조건부 Rendering시 주의점 (0) | 2023.03.01 |
Styled-components props 전달 (0) | 2023.02.18 |
[React] Back 버튼으로 Modal 제어하기(2) (0) | 2023.02.09 |
[React] Back 버튼으로 Modal 제어하기(1) (0) | 2023.02.07 |
댓글 영역