How to Use callBack With setState in React

Full Stack Engineer

Today we are going to explore the callback function in setState and get to know about how we can use it.

First of all, I’d like to explain the ‘callBack’ and ‘setState’.

  1. callBack functions is a function that is passed as an argument to another function, to be “called back” at a later time. These functions can be used synchronously or asynchronously.
  1. State can be updated in response to event handlers, server responses or prop changes. React provides a method called setState for this purpose.

setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state.

To update the state of a component, we use the setState method. However it is easy to forget that the setState method is asynchronous, making it difficult to debug code. The setState function also does not return a Promise. Even using async/await or anything similar will not work.

When the state is actually set can vary. Usually it happens on the next render, but it can sometimes be batched for performance. The setState function takes an optional callback parameter that can be used to make updates after the state is changed.

So, basically to perform an action such as making an AJAX request or throwing an error, after calling setState in a react component we use setState Callback function.

setState Callback in a Class Component

Let’s take an example to understand how a setState callback works inside a react class component.

Open your terminal and follow along:

Create a new project by the following command:

 npx create-react-app challan-generator

where, challan-generator is the project name.

Now, go to the project directory and start it-

cd challan-generator
npm start

You should have your project started in the localhost.

Inside your project, create a new file ChallanGenerator.js or whichever name you prefer and start writing this code.

import React from 'react';
import ChallanGenerator from "./ChallanGenerator";
function App() {
 return (
   <div className="App">
    <ChallanGenerator/>
   </div>
 );
}

export default App;

You will see the following in your browser:

In the above example we are passing a speed value via input field which sets the state via onChange listener.

Focus on the checkSpeed function. That’s where the setState function gets called. Look at the second argument inside that setState function: it’s calling checkSpeed.

That’s the callback function which will be executed for either making AJAX requests or for any other specific task which needs to be done as soon as the speed is updated. In our case it’s checking whether the speed is under limit or over limit and proceeds as per the condition.

useState Callback in A Functional Component

Now with the introduction of React Hooks, we can ‘useState’ in functional components too. React hooks provide useState to define states inside functional components.

But here as well the same problem arises as it does in ‘setState’. Also useState doesn’t provide any ‘callBack’ of it’s own so to overcome this we can use ‘useEffect’ hooks as a ‘callBack’.

In the simplest terms, useEffect is a Hook that allows you to perform side-effects in functional components. For even more detail, these effects are only executed after the component has rendered or if any of its dependency changes, therefore not blocking the render itself.

Let’s implement the same function we implemented for the above setState Callback.

Again start with creating a new file ChallanGenerator.js and this time it’ll be a functional component.

mport React, { useEffect, useState } from 'react';

function ChallanGenerator() {
  const [speed, setSpeed] = useState(0);

  const updateSpeed=(value)=> {
    setSpeed(value);
  };

  useEffect(() => {
    if (speed !== 0 && speed>70) {
 // Make API call to /generate Challan
    } else {
 // Throw error 404, challan not found
    }
  }, [speed]);  	//once the speed is updated useEffect executes

  return (
    <div>
      <p>Challan Generator</p>
      <input
        type="number"
        value={speed} 
        placeholder='miles per hour'
        onChange={e => updateSpeed(e.target.value)}
      />
    </div>
  );
}
export default ChallanGenerator;

useEffect hook takes a dependency array as a second argument in which we pass the dependency parameter. In the above example, as soon as the speed (state) is updated via input field the useEffect function executes as it depends on speed.

Hence, the same work which we did with the help of setState callBack can be done in this effect providing the desired output in functional Components too.

Hope you guys have a clear idea now as to how setState callback can be helpful when working with states in react’s class-based components and how we can achieve the same in functional components too.

Share your views in the comment section below!

What does the callback function do?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of tasks like make API call, throw an error, etc.

Does useState have a callback?

No, useState does not have callBack but you can achieve this behavior using useEffect hook.

Why is setState asynchronous in react?

setState actions are asynchronous and are batched for performance gains. This is explained in the documentation of setState

Can a callback function return a value?

No, it does not return a value, it just executes the callback with the result.

image

How useful was this post?

Please do Rate Us and Share!

Related Blogs

About The Author

Lucas is a passionate software engineer with over fifteen years of experience developing software under both web and Windows environments. He specializes in Node.js and .NET frameworks, as well as React and AngularJS on the front-end. Lucas holds a Master’s degree in computer science and has worked with a variety of Agile teams. He communicates extremely well.

Author: admin

Leave a Reply

Your email address will not be published.