Setstate Tutorial React
Setstate Tutorial React
Setstate Tutorial React
constructor(props) {
super(props)
state = {
searchTerm: ''
•React instructs the search component to update the value and the
search term is merged in
<Search />
</div>
// new
<span>
<Search />
</span>
All <div> tags become <span> tags and the whole component tree
will be updated as a result.
The rule of thumb is to never mutate state directly. Always use
setState() to change state. Modifying state directly, like the snippet
below will not cause the component to re-render.
// do not do this
this.state = {
searchTerm: event.target.value
}
Passing a Function to `setState()`
To demonstrate this idea further, let’s create a simple counter that
increments and decrements on click.
Let’s register the component and define the markup for the :
state = { count: 0 }
handleIncrement = () => {
handleDecrement = () => {
render() {
return (
<div>
<div>
{this.state.count}
</div>
</div>
}
At this point, the counter simply increments or decrements the
count by 1 on each click.
But what if we wanted to increment or decrement by 3 instead?
We could try to call setState() three times in the handleDecrement
and handleIncrement functions like this:
handleIncrement = () => {
handleDecrement = () => {
{},
{ count: this.state.count + 1 },
{ count: this.state.count + 1 },
{ count: this.state.count + 1 },
{count: count + 3}
);
console.log(object);
…we can now increment count three times with one click.
In this case, instead of merging, React queues the function calls in
the order they are made and updates the entire state ones it is
done. This updates the state of count to 3 instead of 1.
Access Previous State Using Updater
When building React applications, there are times when you’ll
want to calculate state based the component’s previous state. You
cannot always trust this.state to hold the correct state immediately
after calling setState(), as it is always equal to the state rendered
on the screen.
Let’s go back to our counter example to see how this works. Let’s
say we have a function that decrements our count by 1. This
function looks like this:
changeCount = () => {
this.changeCount()
this.changeCount()
this.changeCount()
this.setState((prevState) => {
})
}
Now we are not depending on the result of this.state. The states of
count are built on each other so we are able to access the correct
state which changes with each call to changeCount().
setState() should be treated asynchronously — in other words, do
not always expect that the state has changed after calling
setState().
Wrapping Up
When working with setState(), these are the major things you
should know:
•Update to a component state should be done using setState()