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

Ace Lennox
16 Jan 20252 minutes to read

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


Recent Posts

Latest Posts


logo

Explore insightful articles and tutorials on programming, web development, and mobile app creation. Dive into topics like ReactJS, Next.js, Android, iOS, and modern coding practices. Learn with practical examples and tips for building robust, responsive, and high-performing applications. Perfect for developers of all levels seeking to enhance their skills.

Social

© 2025. All rights reserved