Search code examples
node.jsreactjswebreact-hooks

use Effect not working in react. the error is saying Uexpected token in the web console


I am using use effect in react js and it seems that it has a problem if I use 'effect' in my react app then it gives me an error saying "Unexpected token"

import React, { Component , useEffect} from 'react'

class Effect extends Component {


  useEffect(() => {
    console.log('Effect');
  })
  

  constructor() {
    super()

    this.state =
    {
      count :0
    }
    this.CH = () =>
    {
      this.setState(PS =>{
        console.log(PS);
        return {count:PS.count +1}
      })
    }
  }

  render()
  {
    return(
      <>
      <button onClick={this.CH}>
      </button>

      <p>
        {`You have clicked me ${this.state.count} times.`}
      </p>

      </>
    )
  }
}


export default Effect

and this is the useEffect code:

useEffect(() => {
    console.log('Effect');
  })
  

so i followed some vids and it seems to not work for me they were using this in function based component . but i am not, so the the problem us this only?


Solution

  • You can only use useEffect on Functional-based components! On class-based you have some alternatives: componentDidMount()

    Docs: https://reactjs.org/docs/react-component.html#componentdidmount

    Suggestion: if you are creating a new react app most of the time the best thing to do is to use function components. Source: https://djoech.medium.com/functional-vs-class-components-in-react-231e3fbd7108#:~:text=The%20most%20obvious%20one%20difference,which%20returns%20a%20React%20element.