DEV Community

Discussion on: Why to use useState in react?

Collapse
 
eerk profile image
eerk • Edited

Don't forget the this.state object that is available in class App(). I'm curious about when to use useState and when to use this.state.

Collapse
 
aasthapandey profile image
Aastha Pandey

I think when we use function component, we use the hook useState() and when we are using class component we use this.state.
I've never used class component or this.state.

Collapse
 
peerreynders profile image
peerreynders

If you are used to using this.state in class components then useState() in function components can seem a bit magical.

For me Getting Closure on React Hooks made that magic go away.

In class components React manages the component instance specific data that is relevant to rendering in this.state and this.props.

A function component is roughly equivalent to a class component that has been stripped down to its render() method - which is now being used as a standalone function where the props are passed in as the arguments - but there is no equivalent for this.state in a pure function.

That is why function components get access to component instance specific data via React hooks (like useState()) - which make the function impure. But because of how React manages the component instance specific data one has to follow the Rules of Hooks - breaking them can lead to surprising bugs.

Collapse
 
eerk profile image
eerk

Nice explanation! The mysterious part to me is where is the state kept when using useState, if not in the function and not in a class instance... 😎

Thread Thread
 
peerreynders profile image
peerreynders

Deep dive: How do React hooks really work? was the version of the article I meant to link to.
Thread Thread
 
eerk profile image
eerk

this is one of the hardest concepts of javascript for some reason. Getting slightly off-topic here.

this