React のフック — 概要

Jan 21 2023
バージョン 16.8 の React にフックが追加され、React の機能コンポーネントで状態を使用できるようになりました。
反応ロゴ

バージョン 16.8 の React にフックが追加され、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>
      );
    }