React state를 deep~하게 알아보기

Heewon👩🏻‍💻·2024년 5월 1일
function App() {
      const [counter, setCounter] = React.useState(0);
      const onClick = () => {
        setCounter(counter + 1);
      };
    }

setCounter(counter +1);
여기서 counter는 state에 지정된 변수를 다이렉트로 사용하고 있는데 이때 문제점이 예상치 못한 곳에서 counter에 업데이트가 일어날 수 있고(지금은 버그 증명을 할 수 없으나 빈번하게 일어나는 일이라고한다..), 그렇게되면 기대하는 counter의 데이터를 불러 올 수 없다.
문제점을 해결하려면 함수를 변수로 넘겨주면된다.

const onClick = () => {
	setCounter((1. current) => 2. current+1);
    
    1. 첫번째 argument = 현재값.
    2. 함수의 return 값 = 새로운 state.
}

이해하기 어렵다면!!!

1번

const [counter, setCounter] = React.useState(0);
      const onClick = () => {
        setCounter(counter + 1);
        setCounter(counter + 1);
        setCounter(counter + 1);
        setCounter(counter + 1);
        setCounter(counter + 1);
 };

2번

const [counter, setCounter] = React.useState(0);
const onClick = () => {
		setCounter((current) => current + 1);
        setCounter((current) => current + 1);
        setCounter((current) => current + 1);
        setCounter((current) => current + 1);
        setCounter((current) => current + 1);
 };

위 코드를 각각 실행시켜보면 이해가 쉬움.

1번에서 counter에 0이 초기값으로 셋팅되어있고, onClick함수가 실행되었을때, 화면에 출력되는 값은 setCounter을 여러번 호출했음에도, 1이된다. 이유는? Counter이 함수내에서 업데이트가 되지 않기때문이다. 즉 개발자가 의도하려는 바는 5씩 증가를 기대했음에도 결과는 다르다. (물론 Counter +5로 하면되잖아요!! 하면 할말없음. 여기선 과정을 보여주기위함)

2번에서 current에는 현재값 0이 들어가져있고, return값으로 1이들어가게된다. onClick함수 내에서 업뎃이 되며, 아래줄로 내려가면서 계속 current value가 바뀐다.

profile
Interested in coding, meat lover, in love with dogs , enjoying everything happens in my life.

0개의 댓글