Created
May 19, 2020 01:28
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class App extends React.Component { | |
| componentDidMount() { | |
| // BAD! | |
| const [state, setState] = React.useState(null) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function App() { | |
| return ( | |
| {/* BAD! */} | |
| <button onClick={() => React.useState(null)}>Button you can click</button> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function App() { | |
| React.useEffect(() => { | |
| // BAD! | |
| const [state, setState] = React.useState(null); | |
| }); | |
| return ( | |
| <div>Custom component markup</div> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // BAD! | |
| const [globalState, setGlobalState] = React.useState(null); | |
| function App() { | |
| return ( | |
| <div>Custom component markup</div> | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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