React - How to use the setState Callback
In this tutorial, we are going to learn about the how to use the callback function in react setState method with the help of examples.
setState() method
In react, the setState()
method is used to update the component state.
whenever we call a setState method react will re-render the component with an updated UI.
setState(updater,callback)
Note: The setState( ) method doesn’t guarantee you to update the component state immediately so that we can’t rely on the
this.state
after calling setState, instead of that we can use the setState callback.
The setState callback function is invoked, once a setState
update is completed and the component is re-rendered.
Using the setState callback (class components)
To use the setState callback, we need to pass the callback function as an second argument to the setState()
method.
In this example, we are using the setState callback function to make an API call after a setState update is completed.
import React from "react";
class App extends React.Component {
state = {
count: 0
};
increment = () => {
this.setState(
{ count: this.state.count + 1 },
this.checkCount // callback );
};
checkCount = () => {
if (this.state.count >= 10) { fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(json => console.log(json));
}
};
render() {
return (
<div className="App">
<p>{this.state.count}</p>
<button onClick={this.increment}>increment</button>
</div>
);
}
}
export default App;
The setState callback function this.checkCount
is called once a this.state.count
value is incremented.
Inside the this.checkCount
function we added a following condition (this.state.count >= 10) to make the api call.
Using the setState callback in hooks
In functional components, we can use the state by using a useState()
hook but there is no second argument to add a callback to it.
Instead of we can use the useEffect()
hook.
Example:
import React, { useState, useEffect } from "react";
function App() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
const checkCount = () => {
if (count >= 10) {
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(json => console.log(json));
}
};
// useEffect hook runs when a count value is changed
useEffect(() => {
checkCount(); }, [count]);
return (
<div className="App">
<p>{count}</p>
<button onClick={increment}>increment</button>
</div>
);
}
In the above code, we have passed the second argument to the useEffect()
hook which is an array with count
value ([count]
), so that the useEffect hook will run the callback function when a count
value is changed.