ppedrazzi
ppedrazzi

Reputation: 787

Invalid Hook Call Error when using react useState hook inside firebase app

I am trying to get react hooks to work. Here is the function component:

function useHooksExample() {
  const [foo, setFoo] = useState(0);
  setFoo(5);
  return foo;
}

I call this via:

useHooksExample();

I get an error as follows:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app.

I've debugged and confirmed I am using a single react version. Perhaps I am using state hooks incorrectly?


Here is where I am calling the custom hook from:

    class TableData extends Component {
       componentDidMount() {
        useHooksExample();
   }
}
    export default TableData;

Upvotes: 1

Views: 1237

Answers (1)

Ross Allen
Ross Allen

Reputation: 44880

Hooks are only for use inside function components. You can convert TableData into a function component in order to use your hook:

export default function TableData() {
  const foo = useHooksExample();
  return <div />;
}

This is covered in the "Only Call Hooks from React Functions" section of the Rules of Hooks.

Upvotes: 1

Related Questions