React Hooks

React Hooks, introduced in version 16.8, revolutionized how we manage state and other React features in functional components. Before hooks, class components were essential for handling state and lifecycle methods, but hooks allow us to use these features within functional components, often simplifying our code and improving readability. Even though hooks have largely replaced the need for class components, there are no plans to remove classes from React.



What are Hooks?

Hooks allow us to “hook” into React features such as state management and lifecycle methods directly within function components. This means you can manage component state and side effects without writing a class.




Example of a React Hook

In this example, we’re using the useState hook to manage the state of our component. Specifically, the useState hook keeps track of our application’s state—in this case, our favorite animal.

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

function FavoriteAnimal() {
  const [animal, setAnimal] = useState("cat");

  return (
    <>
      <h1>My favorite animal is {animal}!</h1>
      <button
        type="button"
        onClick={() => setAnimal("dog")}
      >Dog</button>
      <button
        type="button"
        onClick={() => setAnimal("cat")}
      >Cat</button>
      <button
        type="button"
        onClick={() => setAnimal("bird")}
      >Bird</button>
      <button
        type="button"
        onClick={() => setAnimal("fish")}
      >Fish</button>
    </>
  );
}

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




How to Use Hooks

You must import hooks from React. Here, we’re using the useState hook to handle the state of our application.

import React, { useState } from "react";


State Management with Hooks

State refers to data or properties that need to be tracked in your application. The useState hook returns an array with two elements: the current state value and a function to update it. We can destructure these values and use them within our function component.



Rules of Hooks

There are three fundamental rules to keep in mind when using hooks:

  1. Only Call Hooks Inside Function Components: Hooks cannot be used in regular JavaScript functions; they must be used within function components.
  2. Only Call Hooks at the Top Level: Hooks should be called at the top level of your component, not inside loops, conditions, or nested functions.
  3. Hooks Cannot be Conditional: Ensure hooks are always called in the same order each time a component renders.

Note: Hooks will not work in React class components.

Scroll to Top