States in React are objects that are used to store data and affect how the component renders. They're managed completely within the component and can be changed over time (by things like user actions and API requests).
As we know, components can have an initial state set. For example:
import React, { Component } from 'react';
class Accessories extends Component {
constructor() {
super()
this.state = {
jewelry: ['bracelet', 'earrings']
}
}
}
...
An alternative way to set state is using setState()
. This function tells React that the component (and its children) need to be re-rendered with the updated state. componentDidMount()
is a great place to call this function, as it's invoked immediately after a component is mounted. If you call setState()
in componentDidMount
, it will trigger an extra rendering, but it will happen before the browser updates the screen thus render()
will be called twice. Here's an example:
import React, { Component } from 'react';
class Accessories extends Component {
constructor() {
super()
this.state = {
jewelry: []
}
}
}
componentDidMount() {
this.setState({
jewelry: 'bracelet', 'earrings'
})
}
...