Curriculum
Course: React
Login

Curriculum

React

Text lesson

What is a Hook?

Introduced in React version 16.8, Hooks enable function components to access state and other React features, reducing the need for class components.

While Hooks generally replace class components, React has no plans to remove class components.

What is a Hook?

Hooks enable us to “hook” into React features, including state and lifecycle methods.

Example:

Here is an example of a Hook. Don’t worry if it’s not clear yet; we’ll cover it in more detail in the next section.

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

function FavoriteColor() {
 const [color, setColor] = useState("red");

 return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button
        type="button"
        onClick={() => setColor("blue")}
      >Blue</button>
      <button
        type="button"
        onClick={() => setColor("red")}
      >Red</button>
     <button
        type="button"
        onClick={() => setColor("pink")}
      >Pink</button>
      <button
        type="button"
        onClick={() => setColor("green")}
      >Green</button>
    </>
 );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);

You need to import Hooks from React. In this example, we’re using the useState Hook to manage the application state. State typically refers to data or properties within an application that need to be monitored.

Hook Rules

There are three rules for using Hooks:

  1. Hooks can only be called inside React function components.
  2. Hooks must be called at the top level of a component.
  3. Hooks cannot be called conditionally.
Note: Hooks do not work in React class components.

Custom Hooks

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

We’ll explore this further in the Custom Hooks section.