What is the purpose of callback function as an argument of setState event ?
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.
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.
Step to Run Application: Run the application using the following command from the root directory of the project:
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.
Please Login to comment...