Categories
React Answers

How to Fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ Error When Developing React Apps?

Spread the love

Sometimes, we may run into the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps.

In this article, we’ll look at how to fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps.

Fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ Error When Developing React Apps?

To fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps, we should call hook functions only in function components at the top level.

They also shouldn’t be called inside async code.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [val, setVal] = useState("green");

  return (
    <>
      <button onClick={() => setVal(val === "green" ? "red" : "green")}>
        click me
      </button>
      <p>{val}</p>
    </>
  );
}

to call the useState gook at the top level.

And then we can use its returned values in the JSX code.

The hooks must be called at the top level and in synchronous code only so that React can keep track of the order the hooks are called.

Conclusion

To fix the ‘Invalid hook call. Hooks can only be called inside of the body of a function component’ error when developing React apps, we should call hook functions only in function components at the top level.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *