-2

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

constructor

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

1 Answers1

0

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.

J2R
  • 148
  • 2
  • 11