Author -  Sai gowtham

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.

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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY