State is a weird concept to wrap your head around. But I hope this short read will help you conceptualize this core concept.
Key takeaway
React state makes it so that when your state data changes, React triggers a re-render of your components, which then updates the DOM accordingly.
So as a developer, you won't have to worry about getting the right elements to change the DOM because React will handle that.
Getting started with state
Setting the initial state
This can be done with a constructor of like this:
state = {
toggleOn: true
};
Updating the state
State can be updated with setState
. Never update state directly with state =
this.setState{toggleOn: false}
How it all comes together
(codepen
class Toggle extends React.Component {
state = {
toggleOn: true
};
handleClick= () => {
this.setState(prevState => ({
toggleOn: !prevState.toggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.toggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
Difference between State and Props
- Any data your components use will accessed in state or in props
- State is internally maintained (rather than being passed in like prop)
- State lets us update the information in a component without requiring its parent to somehow send updated information
- You initial state in the constructor
If you're still confused, below is a (very) simplified test for determining if a component should have state. Start by understanding what isn't/doesn't have state
no state
- if a component is passed its data through its props, that piece of data should not be in the state
- if a component/data remains unchanged over time, it doesn't need/isn't state
state
- if a component holds data, it may have state
- if a component sets data for its child components, it may have state
Here is a great article with a more depth look at React state
Top comments (1)
Thanks for the headsup. I haven't reviewed hooks yet, but I think it will be worth an update to either this post or a new one once I get there
With each blog post, I want to provide a 1 min summary of each React concept as I learn it. Do you see anything else that's either wrong or worth additional exploration?