How to Use Callback Function of setState in React
In computer programming, a callback, also known as a “call-after” function, is any executable code that is passed as an argument to other code. In this article, we’re going to see how to use setState callback function in React.
Table of Contents
Callback in a Class Component
Let’s see an example of callback in a class component:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
age: 0,
};
}
// this.checkAge is passed as the callback to setState
updateAge = (value) => {
this.setState({ age: value}, this.checkAge);
};
// callback function
checkAge = () => {
const { age } = this.state;
// condition goes here
console.log(age);
};
render() {
const { age } = this.state;
return (
<div>
<p>Age Checker</p>
<input
type="number"
value={age}
onChange={e => this.updateAge(e.target.value)}
/>
</div>
);
}
}
export default App;
In the example, we’re taking age from the input field. On changes age input, the value of age changes inside of its state. And at the same time, checkAge()
function gets called.
The checkAge()
function is the callback function and we can set condition in the function.
Callback in a Functional Component
Let’s try to do the same thing in a functional component:
import React, { useEffect, useState } from 'react';
function App() {
const [age, setAge] = useState(0);
// callback function
useEffect(() => {
// condition goes here
console.log(age);
}, [age]);
return (
<div>
<p>Age Checker</p>
<input
type="number"
value={age}
onChange={e => setAge(e.target.value)}
/>
</div>
);
}
export default App;
The useEffect()
function executes at the moment of the age state variable changes.
That’s it. Thanks for reading. ?It’s the equivalent of the setState callback function inside of React class components.
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)