useState()

박민주·2021년 7월 7일
0

REACT

목록 보기
1/4

useState는 [state, setState]
첫 번째 인자인 state를 제공하고,
state와 state를 변경 할 두 번째 인자 setState 함수를 반환한다.
또한, initialState를 파라미터로 받는다.

const Example = () => {
const [count, setCount] = useState(3);

비구조화 할당 문법을 통해 state에는 count를
setState엔 setCount로 받아서 사용할 수 있다.
setCount로 count state를 변경하면 렌더링이 다시 일어남.
Example은 함수이기 때문에, 렌더링 할 컴포넌트 대신에
값을 반환할 수 있음.

import { useState } from 'react';

const Example = () => {
  const [count, setCount] = useState(0);
  
  return (
    <div>
      <p>{`count: ${count}`}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  )
};

export default Example;
  1. import { useState } from 'react';
  2. const [count, setCount] = useState(0);
    count에는 state 값을 넣고, setCount에는 count라는 state값을 수정한다.
  3. useState(0);
    useState(0)의 초기값은 0
  4. <button onClick={() => setCount(count + 1)}>+</button>
    이벤트 리스너를 사용하여 버튼을 클릭할때마다,
    count의(state) 숫자가 1씩 증가하여 setCount(setState)에서 업데이트.
  5. <p>{`count: ${count}`}</p>
    count(state)가 증가하는 상황을 P 태그 안에서 백틱으로 나타내줌.
profile
개발공부

0개의 댓글