Skip to content

Commit

Permalink
Fix the issue of sudheerj#254
Browse files Browse the repository at this point in the history
  • Loading branch information
chetannada committed May 24, 2023
1 parent 0057256 commit 552014a
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -773,14 +773,36 @@
12. ### What is the purpose of callback function as an argument of `setState()`?
The callback function is invoked when setState finished and the component gets rendered. Since `setState()` is **asynchronous** the callback function is used for any post action.
`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.

**Note:** It is recommended to use lifecycle method rather than this callback function.
```javascript
setState({ name: "John" }, () =>
console.log("The name has updated and component re-rendered")
);
```jsx
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;
```
**[⬆ Back to Top](#table-of-contents)**
Expand Down

0 comments on commit 552014a

Please sign in to comment.