Skip to content

Instantly share code, notes, and snippets.

@owenconti
Created May 19, 2020 01:28
Show Gist options
  • Select an option

  • Save owenconti/692d52e80241c2164a94245145792f38 to your computer and use it in GitHub Desktop.

Select an option

Save owenconti/692d52e80241c2164a94245145792f38 to your computer and use it in GitHub Desktop.
"Hooks can only be called inside the body of a function component" ReactJS error
class App extends React.Component {
componentDidMount() {
// BAD!
const [state, setState] = React.useState(null)
}
}
function App() {
return (
{/* BAD! */}
<button onClick={() => React.useState(null)}>Button you can click</button>
);
}
function App() {
React.useEffect(() => {
// BAD!
const [state, setState] = React.useState(null);
});
return (
<div>Custom component markup</div>
);
}
// BAD!
const [globalState, setGlobalState] = React.useState(null);
function App() {
return (
<div>Custom component markup</div>
);
}
function App() {
const [state, setState] = React.useState(null);
// Use the state in `useEffect`
React.useEffect(() => {
axios.get(`/api/${state}`);
});
return (
<div>
<button onClick={() => {
// Use the state inside an event handler
setState(state + 1);
}}>Click this button</button>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment