Nui
Nui

Reputation: 53

Where to use Usestate hook in react component

I am trying to use UseState hook in react but I am not sure where to define it. I tried to declare it in React component but compiler gives an error

class VoiceCallComponent extends React.Component {
  const [val, setVal] = React.useState(7);
  
  ..
  ..
  ..
}

Above code throws an error saying identifier requires.

enter image description here

Upvotes: 0

Views: 72

Answers (1)

Johan
Johan

Reputation: 2962

You cannot use useState in a class component. You need a functional component.

Here is the doc

Here is the code for your example :

import React, { useState } from 'react';

function VoiceCallComponent() {
  const [val, setVal] = useState(7);

  // rest of the component logic goes here
  return (
    // JSX
  )
}

Upvotes: 4

Related Questions