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

Ace Lennox
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
Only call Hooks inside React function components.
Call Hooks at the top level—avoid loops, conditions, or nested functions.
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