React is a UI library that renders components written in JSX. You can build and render any components as per your usage. It introduces the concept of state. Whenever there is a change in state component gets re-rendered. The states are used to store data for specific components. These states can be updated accordingly using setState function. You can assign meaningful names to states. There can be a requirement to perform some action only after the state has updated. We can do this in React.
SetState is an asynchronous method. Asynchronous means that the remaining code will get executed while the current action is being performed. Whereas synchronous code will block the code execution while the current action is being performed. So, if you want an action to be performed only after the state has been updated you can make use of a call back function. This callback function is put as an argument to setstate method. This is the exact purpose of defining a callback function as an argument of setState.
Approach: Let us create a React project and then we will create a UI to showcase the above purpose. The user will update the state and then only action will be performed through the callback function.
Creating React Project:
Step 1: Create a react application by typing the following command in the terminal.
npx create-react-app project_name
Step 2: Now, go to the project folder i.e. project_name by running the following command.
cd project_name
Project Structure: It will look like the following:
Example: Let us create a button that will act as a counter. Users can click on the button to increase the value. Only after the state updates i.e. the value increases the user can see the updated value in UI.
App.js
Javascript
import React from "react" ; class App extends React.Component { constructor() { super (); this .state = { value: 0 } } call() { this .setState({ value: this .state.value + 1 }, () => console.log( "Updated Value :" + this .state.value) ); } render() { return ( <div> <button onClick={() => { this .call() }}> Click to update state! </button> </div> ); } } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Open your browser. It will by default open a tab with localhost running. The user clicks on the button to increase the value. As you can see in the output shown in the image an alert is called showcasing the updated value.