How can i use {useState} inside ComponentDidMount in ReactJS

Viewed 47
const [bgColor, setBgColor] = useState('black');
class Accelerons extends Component {
constructor(props) {
super(props);
}
componentDidMount = () => {
$(window).on('scroll touchmove', function () {
  if ($(document).scrollTop() >= $('.about-us').position().top) {
    setBgColor('red');
  }
  
 });
 };
render() {
return (
  <article
    style={{
      backgroundColor: bgColor,
    }}
  >
    <Overlay />
    <Landing landing={DataAccelerons.landing} />
    <AboutUs itemColor={itemColor} accelerons={DataAccelerons} />
    <Participation itemColor={itemColor} accelerons={DataAccelerons} />
    <TeamMembers itemColor={itemColor} accelerons={DataAccelerons} />
    <Results itemColor={itemColor} accelerons={DataAccelerons} />
    <Footer
      accentColor={DataAccelerons.accentColor}
      footerColors={DataAccelerons.footerColors}
    />
  </article>
);
}
}
export default Accelerons;

This gives me an error that we can't use react hooks at the starting ,but if I declare them in render it won't be recognized by ComponentDidMount function ReactJS

2 Answers

You can use hooks such as useState only inside functional component whereas setState in the lifecycles in Class components. You don't wanna mix two. A typical usage would go something like this:

import React, { useState } from 'react';

function Example() {
  const [myVal, setMyVal] = useState('Hello World');

  return (
    <div>
      <p>{myVal}</p>
    </div>
  );
}

Read More

If you want to go with lifecycle methods (such as componentDidMount), you may consider using seState. Also, you can't use setState inside render method as it would trigger an infinite call.

React hook can be used only functional component whereas componentDidMount is the life cycle method for class based component.

Related