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 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
useMemo
,
useReducer
, 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 handler13 setState(state + 1);14 }}>Click this button</button>15 </div>16 );17}
Hopefully you found this article useful! If you did, share it on X!
Found an issue with the article? Submit your edits against the repository.