프론트엔드/React

useState로 Map 타입 업데이트하기

deep__sea 2023. 9. 14. 13:11
728x90

state 타입이 Map 타입입니다.

업데이트는 되지만 re-렌더링이 되지 않아 업데이트된 상태를 받지 못하는 상황!

아래와 같이 작성해야 한다.

type dataMapType = Map<string, string>;

const [data, setData] = useState<dataMapType>();

const handleChangeData = (e: SlelectChangeEvent) => {
	data.set(e.target.name, e.target.value);  // data의 key값이 e.target.name과 같다는 저제
    const entries = [...data];
    setData(new Map(entries);
}

참고 : https://stackoverflow.com/questions/66525224/usestate-hook-not-working-on-updating-map

 

useState hook not working on updating map

I am using a useState hook to store a Map const [optionList, setOptionsList] = useState(new Map([ [ uuidv1(), { choice: "", } ]...

stackoverflow.com

React shallow compares the old state and the new state values to detect if something changed. Since it's the same Map (Map's items are not compared), React ignores the update.

참고 글을 보면 리액트는 얕은 비교만 할 뿐 Map의 item들은 비교하지 않는다고 합니다. 그래서 update된 상황을 무시한다고 합니다. }

개발하면서 처음 알았습니다. 그도 그럴 수 밖에 없는 게, 상태 타입을 Map 타입으로 사용한 적이 없던 것 같습니다.. 

 

끗!

728x90
반응형