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.
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.
Don't forget the
this.state
object that is available inclass App()
. I'm curious about when to useuseState
and when to usethis.state
.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.
If you are used to using
this.state
in class components thenuseState()
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
andthis.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 theprops
are passed in as thearguments
- but there is no equivalent forthis.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.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... 😎Deep dive: How do React hooks really work? was the version of the article I meant to link to.
this
is one of the hardest concepts of javascript for some reason. Getting slightly off-topic here.