Programming/React

useState의 렌더링, 함수형 업데이트

한우콩 2023. 4. 28. 19:28

쓰니까 쓰지말고 뭔지 알고 쓰자

 

useState의 setter 함수는 비동기적으로 실행된다.

대표적인 예시로 1씩 카운트가 증가하는 코드가 있다.

 

const [count, setCount] = useState(0);

const countHandler = () => {
 setCount(count + 1);
 setCount(count + 1);
 setCount(count + 1);
}

 

위 코드의 count 결과값은 1이다.

React는 렌더링 최적화를 위해 setState연산이 한꺼번에 수행되며 이는 배치(일괄)로 처리하기 때문이다. 

 

📌 함수형 업데이트

그렇다면 이전 상태를 참조해 동기적인 업데이트를 수행하고 싶다.

이 때 함수형 업데이트를 이용한다.

 

const [count, setCount] = useState(0);

const countHandler = () => {
 setCount(prevCount => prevCount + 1);
 setCount(prevCount => prevCount + 1);
 setCount(prevCount => prevCount + 1);
}

 

📌 함수형 업데이트의 사용 이유

  • 함수형 업데이트는 이전 상태값을 직접 참조하지 않고 함수의 인자로 받기 때문에 불변성을 지키며 새로운 상태값을 계산 할 수 있다.
  • state나 기타 의존값을 useCallback의 의존성 배열에 지정했는데 해당 함수는 의존값이 변경됐다는 이유로 불필요한 함수 생성 비용이 발생할 수 있음. 이를 해결하기 위해 함수형 업데이트를 사용할 수 있다. (성능 최적화)
// As-is
  const onCreate = useCallback(() => {
    const user = {
      id: nextId.current,
      height,
      weight
    }
    
    setUsers(users.concat(user));
    nextId.current += 1;
    
    setInputs({
      height: '',
      weight: ''
    });
  }, [height, weight, users]);

  
// To-be  
  const onCreate = useCallback(() => {
    const user = {
      id: nextId.current,
      height,
      weight
    }
    
    setUsers(users => users.concat(user));
    nextId.current += 1;
    
    setInputs({
      height: '',
      weight: ''
    });
  }, [height, weight]);

 

 

코드 참조

https://velog.io/@johnque/useState-%ED%95%A8%EC%88%98%ED%98%95-%EC%97%85%EB%8D%B0%EC%9D%B4%ED%8A%B8