Question:
What is the difference between constructor and useState, I tried them both and they work on same solution.UseState
constructor
Answer:
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 throughthis.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.
If you have better answer, please add a comment about this, thank you!