-1

I'm getting the error below when running the example attached at the bottom:

react-dom.development.js:49 Uncaught Error: Hooks can only be called inside the body of a function component.
    at invariant (react-dom.development.js:49)
    at resolveCurrentlyRenderingFiber (react-dom.development.js:11633)
    at useReducer (react-dom.development.js:11830)
    at Object.useState (react-dom.development.js:11824)
    at Object.useState (react.development.js:2574)
    at App.render (<anonymous>:25:35)
    at finishClassComponent (react-dom.development.js:14466)
    at updateClassComponent (react-dom.development.js:14429)
    at beginWork (react-dom.development.js:15233)
    at performUnitOfWork (react-dom.development.js:17940)

class App extends React.Component {
  render() {
    const [name, setName] = React.useState('Mary');
    const [age, setAge] = React.useState(10);

    return (
      <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
      </div>
    );
  }
}

ReactDOM.render(
  <div>
    <App />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
  • According to Docs(https://reactjs.org/docs/hooks-faq.html), "Hooks are a new feature proposal that lets you use state and other React features without writing a class." – Vivek Nov 20 '18 at 05:34

2 Answers2

2

Hooks are not supported within class components and you should instead make it a functional component or not use hooks at all if you still rely on some class component features.

function App() {
  const [name, setName] = React.useState('Mary');
  const [age, setAge] = React.useState(10);

  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
    </div>
  );
}

ReactDOM.render(
  <div>
    <App />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>
Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
0

You may also use like:

class App extends React.Component {
  renderApp() { // function within class component
    const [name, setName] = React.useState('Mary');
    const [age, setAge] = React.useState(10);

    return (
      <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
      </div>
    );
  }
  render() {
    return this.renderApp()
  }
}

This will be helpful further if you want to render something else and also helpful for using other lifecycle hooks:

render() {
  return (
    <div>
     <h1>My App</h1>
     { this.renderApp() }
    </div>
  )
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231