How To Use CallBack With SetState In React

SetState in React
How To Use CallBack With SetState In React

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

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

  1. callBack function 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.
  2. 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 the 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 local host.

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 the input field which sets the state via the 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 that 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 the limit or over the limit and proceeds as per the condition.

react Callback

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 its 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 the 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 to 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!

FAQ

Q1. What is meant by the Callback function?

Ans- 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 routine or action.

Q2. What is the difference between Function & Callback?

Ans- The main difference between a normal function and a callback function can be summarized as follows: A normal function is called directly, while a callback function is initially only defined. The function is only called and executed once a specific event has occurred.

Q3. Are Callbacks Asynchronous?

Ans- Callbacks are not asynchronous by nature, but can be used for asynchronous purposes.