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

  1. Callback in a Class Component
  2. Callback in a Functional Component

Callback in a Class Component

Let’s see an example of callback in a class component:

App.js
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:

App.js
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.

 It’s the equivalent of the setState callback function inside of React class components.

That’s it. Thanks for reading.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.