Understanding setState in React

You may be wondering why my call to setState does not mutate the state immediately, this is because setState calls are asynchronous and are usually bundled together to mutate state later.

But sometimes we need to use the state varaible after the set state this can be done by using the call back function supported in set state. In the code snippet below, i want to update the selectedFile state with file and have to print the file name. Usually the code would be like this

this.setState({selectedFile:file}); console.log(this.state.selectedFile.Name);
Code language: CSS (css)

The above code would definitely print either undefined or previous state of selected file. To avoid the above issue we can re write the above code as below and get desired result.

this.setState({selectedFile: file}, function () { console.log(this.state.selectedFile.Name);
Code language: JavaScript (javascript)