React의 Hooks — 소개

Jan 21 2023
버전 16.8에서 React에 후크가 추가되어 React 기능 구성 요소에서 상태를 사용할 수 있게 되었습니다.
반응 로고

버전 16.8에서 React에 후크가 추가되어 React 기능 구성 요소에서 상태를 사용할 수 있게 되었습니다. 이전에는 클래스 구성 요소만 상태에 액세스할 수 있었습니다. 이 새로운 후크 추가로 반응 상태를 더 쉽게 처리할 수 있습니다.

//handling state in React class component
import React from "react"

class App extends React.Component {

  constructor(props) {    
    super(props);    
    this.state = {name: "Thushitha"};  
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <p>I'm {this.state.name}</p>      
      </div>
    );
  }
}

export default App;

import {useState} from 'react'

  1. React 기능 구성 요소에서만 사용할 수 있습니다.
  2. 구성 요소의 맨 위에서만 호출할 수 있습니다.
  3. //importing required hook from react
    import {useState} from 'react'
    
    export default function App() {
    
      // correctly calling useState hook
      const [name,setName]=useState("Max")
    
      if(name==="Max"){
        //wrong usage as this hook is called conditionally. The hooks have to be 
        //called in the same order in every rendering
        const [school,setSchool]=useState("ABC School");
      }else{
        const [college,setCollege]=useState("XYZ College");
      }
    
      return (
        <div>
          <h1>Hello World!</h1>
        </div>
      );
    }