Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React JS Constructor vs useState what's the difference?

What is the difference between constructor and useState, I tried them both and they work on same solution.

UseState

  const [filterName, setFilterName] = useState("");
  const [robots, setRobots] = useState([]);

vs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

constructor

constructor() {
    super()
    this.state = {
      robots: robots,
      searchfield: ""
    }
  }

>Solution :

Generally, these are two different approaches in React. The constructor type is part of the OOP React approach with the so called class components. There you have class methods instead of functions. And the state is accessed through this.state.<property>.

The other approach is the function components. That’s the more modern way of doing stuff with React. useState() is a React hook, responsible for a particular state.

They work the same, however the function-based approach is getting more and more common, so I would suggest to switch to function components, unless something requires the explicit usage of class components.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading