[React.js] - Part 9. React Hooks - what is a Hook?

Ace Lennox
2025年01月16日読了時間:2分

React introduced Hooks in version 16.8, letting function components handle state and tap into other React features. Class components are still supported, but typically no longer necessary.


What Are Hooks?

Hooks allow function components to “hook” into essential React features like state and lifecycle methods.

Example (using useState):
Here’s a simple component for choosing your favorite food:

import React, { useState } from "react";
import ReactDOM from "react-dom/client";

function FavoriteFood() {
  const [food, setFood] = useState("pizza");

  return (
    <>
      <h1>My favorite food is {food}!</h1>
      <button onClick={() => setFood("pizza")}>Pizza</button>
      <button onClick={() => setFood("sushi")}>Sushi</button>
      <button onClick={() => setFood("tacos")}>Tacos</button>
      <button onClick={() => setFood("pasta")}>Pasta</button>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<FavoriteFood />);

Make sure to import Hooks from react. In this example, the useState Hook manages the food state.


Hook Rules

  1. Only call Hooks inside React function components.

  2. Call Hooks at the top level—avoid loops, conditions, or nested functions.

  3. Hooks don’t work in class components.


Custom Hooks

If you need to reuse stateful logic across multiple components, create your own custom Hooks.

Source Code

The complete source code for this part is available on GitHub


最近の投稿

Latest Posts


logo

プログラミング、ウェブ開発、モバイルアプリ作成に関する洞察的な記事とチュートリアルを探索します。ReactJS、Next.js、Android、iOS、および最新のコーディングプラクティスについて学びます。実践的な例と、アプリケーションを構築するためのヒントを学びます。すべてのレベルの開発者がスキルを向上させるための理想的な場所です。

SNS

© 2025. All rights reserved