useState

열심히하시는개발자·2021년 5월 20일
0
post-thumbnail

useState 좀 더 알아보기 !

1. 배치O

import React, { useState } from "react";

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

  const clickHandler = () => {
    setCount(count + 1);
    setCount(count + 1);
  };
  return (
    <div>
      <h2>{count}</h2>
      <button onClick={clickHandler}>증가</button>
    </div>
  );
};

export default App;

내가 생각했던 코드 동작

상태 값 변경 함수가 2번 쓰였기 때문에 클릭을 할 때 +2가 한 번에 된다고 생각했다.
ex) 0 => 2 => 4 => 6 => ....

실제 코드 동작

내가 예상했던 거와는 달리 클릭을 할 때 마다 +1이 된다.
ex) 1 => 2 => 3 => 4 => ....

그 이유 !

  • 상태 값 변경 함수가 clickHandler 안에 2번 쓰였어도 리액트는 상태 값 변경 요청을 배치로 처리하기 때문에 click를 해도 +1씩 증가한다.
  • onClick 이벤트 헨들러가 리액트 내부에서 입력이 되었기 때문에 배치로 처리가 가능하다.

2. 배치X

import React, { useEffect, useState } from "react";

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

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

  useEffect(() => {
    window.addEventListener("click", clickHandler);
    return () => window.removeEventListener("click", clickHandler);
  });

  return (
    <div>
      <h2>{count}</h2>
      <button onClick={clickHandler}>증가</button>
    </div>
  );
};

export default App;

이벤트 핸들러를 등록해서 사용하는 경우 !

리액트 내부에서 관리가 되지 않기 때문에 배치로 처리가 되지 않는다.

0개의 댓글