by Sai gowtham

How to use the callback in react setState

How to use the callback in react setState

In this tutorial, we are going to learn about the usage of a callback function in react setState method.

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.

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

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course