Hook : useState

2023. 4. 7. 13:52Node js/React

참고한 원문 : https://www.w3schools.com/react/react_hooks.asp

 

React Hooks

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

Hook (훅)은 React v16.8 에서 도입된 기능으로서 state 와 리액트의 여러가지 특성에 액세스할 수 있도록 지원하며 이로 인해 class (리액트 클래스)의 필요성을 없애버렸다. 당분간 class 를 삭제할 계획이 없다고 한다.

 

useState 는 두 가지 값을 반환한다. 첫 번째는 상태값, 즉 state 이고 두 번째는 해당 state 를 업데이트할 때 쓸 함수이름이다.

 

아래 코드에서 color 에는 현재의 state 가 들어가며 setColor("blue") 에 의해 color = "blue" 로 업데이트 할 수 있다.

useState("") 로 초기화함으로써 color 가 string 포맷으로 처리될 것임을 알 수 있다.

import { useState } from "react";

function FavoriteColor() {
  const [color, setColor] = useState("");
}
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';


function FavoriteColor() {
  const [color, setColor] = useState('red');

  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button type='button' onClick={() => setColor('blue')}>Blue</button>
      <button type='button' onClick={() => setColor('red')}>Red</button>
      <button type='button' onClick={() => setColor('pink')}>Pink</button>
      <button type='button' onClick={() => setColor('green')}>Green</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);

'Node js > React' 카테고리의 다른 글

conditional - {true} (O) "true" (X)  (0) 2023.04.07
props  (0) 2023.04.07
React / React Router / Next.js / Gatsby  (0) 2023.04.06
리액트 컴포넌트끼리 중첩하기  (0) 2023.04.06
HTML 을 리액트 컴포넌트로 나누기  (0) 2023.04.06