Owen Conti

"Hooks can only be called inside the body of a function component" ReactJS Error

Posted on under React by Owen Conti.

"Hooks can only be called inside the body of a function component."

This is a common warning that developers run into when starting out with hooks in React. There are 3 possible reasons for this warning:

  • You may have mismatching versions of React and ReactDOM.
  • You may have more than one copy of React running in your application such that the version of React imported by ReactDOM is not that same version that you import in your application.
  • Most common: You're breaking the rules of hooks. You must only call hooks while React is rendering a function component.

The rules of hooks

You cannot call hooks in class components:

1class App extends React.Component {
2 componentDidMount() {
3 // BAD!
4 const [state, setState] = React.useState(null)
5 }
6}

You cannot call hooks inside event handlers:

1function App() {
2 return (
3 {/* BAD! */}
4 <button onClick={() => React.useState(null)}>Button you can click</button>
5 );
6}

You cannot call hooks inside useMemouseReducer, or useEffect:

1function App() {
2 React.useEffect(() => {
3 // BAD!
4 const [state, setState] = React.useState(null);
5 });
6 
7 return (
8 <div>Custom component markup</div>
9 );
10}

You cannot call hooks outside of React altogether:

1// BAD!
2const [globalState, setGlobalState] = React.useState(null);
3 
4function App() {
5 return (
6 <div>Custom component markup</div>
7 );
8}

Instead, call hooks at the top level function of your component:

1function App() {
2 const [state, setState] = React.useState(null);
3 
4 // Use the state in `useEffect`
5 React.useEffect(() => {
6 axios.get(`/api/${state}`);
7 });
8 
9 return (
10 <div>
11 <button onClick={() => {
12 // Use the state inside an event handler
13 setState(state + 1);
14 }}>Click this button</button>
15 </div>
16 );
17}

Thanks for reading this article!

Hopefully you found this article useful! If you did, share it on Twitter!

Found an issue with the article? Submit your edits against the repository.