react hook 의 setState에서 callback function 사용

낭만개발자·2021년 8월 11일
2

React hook 사용 전 class 사용시 setState()사용할때

this.setState({num = 1}, () => {console.log('callback func 호출')});

처럼 사용하면 setState가 호출되기 전에 callback func이 호출되어 전처리를 진행할 수 있다

근데, hook 사용하면 setState() 내에 callback 넣는거 불가 x
에러 뜬다.

https://www.linkedin.com/pulse/provide-callback-usestate-hook-like-setstate-saransh-kataria/

위 글 읽어 보면 setState 두번째 파라미터에 callback Func 넣는 기능 없어졌다고,
useEffect() 써라고 나와있다. 이걸 제법 시간걸려 찾다니

As soon as state would be updated, it would trigger the useEffect hook. The useEffect hook will only be invoked when state changes because of the dependency array. And we can call our callback function inside that hook and get the functionality that we wanted to achieve.

스테이트 값이 업데이트 되자마자 useEffect hook을 불러일으킨다. 의존성 종속 땜에 그 훅은 오직 스테이트가 변해야지 일어난다. 그래서 우리가 원하는 기능을 가진 콜백함수를 그 훅 내부에 넣을 수 있다.

Note: If you want the changes performed in the callback function to be reflected in the component’s rendered output, you would want to use useLayoutEffect instead of the useEffect react hook.

만약 당신이 /랜더된 컴포넌트의 결과물에 반영된 콜백 함수안에 수행된 변화를 원한다면,
useLayoutEffect을 useEffect을 사용하는 것 대신으로 원할 것이다.

profile
낭만닥터와 슬의를 보고 저런 개발자가 되어야 겠다고 꿈꿔봅니다.

2개의 댓글

comment-user-thumbnail
2022년 6월 15일

뜬금없는 말씀이지만...
'개발 반 기획 반 광고 반 마케팅 반' 도합 200%의 직장인 이신가요!!?

글은 잘 읽었습니다. 감사합니다.

1개의 답글