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.
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Don't forget the
this.stateobject that is available inclass App(). I'm curious about when to useuseStateand when to usethis.state.If you are used to using
this.statein 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.stateandthis.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 thepropsare passed in as thearguments- but there is no equivalent forthis.statein 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.
thisis one of the hardest concepts of javascript for some reason. Getting slightly off-topic here.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.