React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)
What is the purpose of callback function as an argument of setState()?
The callback function provided as the second argument to setState is executed after the state has been updated and the component has re-rendered. Because setState() is asynchronous, you cannot reliably perform actions that require the updated state immediately after calling setState. The callback ensures your code runs only after the update and re-render are complete.
Example
jsx
this.setState({ name: "Alex Morgan" }, () => {
console.log("The name has been updated and the component has re-rendered.");
});
When to use the callback?
vbnet
Use the `setState` callback when you need to perform an action immediately after the DOM has been updated in response to a state change. i.e, The callback is a reliable way to perform actions after a state update and re-render, especially when the timing is critical due to the asynchronous nature of state updates in React. For example, if you need to interact with the updated DOM, trigger analytics, or perform further computations that depend on the new state or rendered output.
Note
vbnet
- In modern React (with function components), you can achieve similar effects using the `useEffect` hook to respond to state changes.
- In class components, you can also use lifecycle methods like `componentDidUpdate` for broader post-update logic.
- The `setState` callback is still useful for one-off actions that directly follow a specific state change.